版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xhpscdx/article/details/79840232
Spring boot 和 Redis缓存说明文档
Spring Cache是基于AOP切面和注解来实现缓存的。核心类为Cache
和 CacheManager
。
前者用来定义缓存的一些操作,后者则是Spring的核心缓存SPI(Service Provider Interface),
管理第三方缓存实现统一接入。关系图如下:
缓存的注解介绍
- @EnableCaching 启动cache功能
- @CacheConfig 类级别的缓存注解,允许共享缓存名称。
- @Caching 将多种缓存操作分组(如果一个方法有多个缓存操作可以使用)
- @Cacheable 查询缓存
- @CacheEvict 移除缓存
- @CacahePut 更新缓存
/**
* 根据id来更新记录
* @param histories
*/
@CachePut(key = "'histories'.concat(#histories.id.toString())")
@Override
public void updateHistories(Histories histories) {
try{
historiesMapper.updateHistories(histories);
}catch (DataAccessException e){
throw new ServiceException(e);
}
}
/**
* 根据id来查询记录
* @param histories
* @return
*/
@Cacheable(key = "'histories'.concat(#histories.id.toString())")
@Override
public List<Histories> getHistories(Histories histories) {
try{
return historiesMapper.getHistories(histories);
}catch (DataAccessException e){
throw new ServiceException(e);
}
}
可在缓存中查询结果,是否缓存到
如果需要自定义缓存失效时间等,可以在CacheManager的实现类RedisCacheManager来自定义。
如:
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager manager = new RedisCacheManager(redisTemplate);
// 整体缓存过期时间
manager.setDefaultExpiration(3600L);
Map<String, Long> expiresMap = new HashMap<>();
// 设置缓存过期时间。key和缓存过期时间,单位秒
expiresMap.put("histories", 50l);
manager.setExpires(expiresMap);
return manager;
}
下的redis-spring-example
模块