spring boot + redis 缓存注解使用

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为是
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值