spring boot + redis 缓存注解使用
首先要在入口类中添加 @EnableCaching 注解启动缓存
缓存可以自己定义 也可以使用默认的。
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
//全局redis缓存过期时间
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofDays(1));
RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisTemplate.getConnectionFactory());
return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
}
定义key生成方式,也可以不定义
@Bean("userKeyGenerator")
public KeyGenerator keyGenerator(){
return (target, method, params) ->{
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(target.getClass().getName());
Arrays.stream(params).forEach( param -> stringBuffer.append(param.toString()));
return stringBuffer.toString();
};
}
在service中添加注解
@Cacheable(value = "user", keyGenerator = "userKeyGenerator")
public User findById(Integer id){
return userMapper.findById(id);
}
@CachePut(value = "user", key= "#root.targetClass.name + #result.id.toString()")
public User saveUser(User user){
userMapper.saveUser(user);
return user;
}
@CacheEvict(value = "user", keyGenerator = "userKeyGenerator" )
public void deleteUser(Integer id){
userMapper.deleteUser(id);
}
@Cacheable详解
该注解有value,cacheNames,key,keyGenerator,cacheManager,cacheResolver ,
condition,unless,sync 九个属性
value 与 cacheNames指定缓存名称
key 用来指定在缓存中的key
keyGenerator 用来指定key得生成方式
cacheManager 用于指定使用哪个缓存管理器
cacheResolver 用于指定使用哪个缓存解析器
condition 用于指定缓存条件 为true则缓存 例如 "#result != null"
unless 用于指定缓存排除条件 为true则不缓存 例如 "#result == null"
sync 同步
@CachePut详解
该注解有value,cacheNames,key,keyGenerator,cacheManager,cacheResolver ,
condition,unless 八个属性
value 与 cacheNames指定缓存名称
key 用来指定在缓存中的key
keyGenerator 用来指定key得生成方式
cacheManager 用于指定使用哪个缓存管理器
cacheResolver 用于指定使用哪个缓存解析器
condition 用于指定修改缓存条件 为true则修改缓存 例如 "#result != null"
unless用于指定不修改缓存排除条件 为true则不修改缓存 例如 "#result == null"
@CacheEvict详解
该注解有value,cacheNames,key,keyGenerator,cacheManager,cacheResolver ,
condition,allEntries,beforeInvocation 九个属性
value 与 cacheNames指定缓存名称
key 用来指定在缓存中的key
keyGenerator 用来指定key得生成方式
cacheManager 用于指定使用哪个缓存管理器
cacheResolver 用于指定使用哪个缓存解析器
condition 用于指定删除缓存条件 为true则删除缓存 例如 "#result != null"
allEntries 是否删除value空间下的所有缓存
beforeInvocation 是否方法执行成功前删除缓存 true为是