Spring cache

Spring cache 整合redis

Spring-boot-starter-cache
Application类上@EnableCaching

1.Cacheable
例子:
@Cacheable(value = “models”, key = “#testModel.name”, condition = "#testModel.address != ‘’ ")
public TestModel getFromMem(TestModel testModel) throws InterruptedException {
TimeUnit.SECONDS.sleep(1);
testModel.setName(testModel.getName().toUpperCase());
return testModel;
}
例子里的注解@Cacheable中存在有以下几个元素
value (也可使用 cacheNames) : 可看做命名空间,表示存到哪个缓存里了。
key : 表示命名空间下缓存唯一key,使用Spring Expression Language(简称SpEL,详见参考文献[5])生成。
condition : 表示在哪种情况下才缓存结果(对应的还有unless,哪种情况不缓存),同样使用SpEL
对于使用@Cacheable标注的方法,Spring在每次执行前都会检查Cache中是否存在相同key的缓存元素,如果存在就不再执行该方法,而是直接从缓存中获取结果进行返回

2.CacheEvict
例子:
@CacheEvict(value = “models”, allEntries = true)
@Scheduled(fixedDelay = 10000)
public void deleteFromRedis() {
}

@CacheEvict(value = "models", key = "#name")
public void deleteFromRedis(String name) {
}

例子里的注解 @CacheEvict 中存在有以下几个元素

  • value (也可使用 cacheNames) : 同Cacheable注解,可看做命名空间。表示删除哪个命名空间中的缓存
  • allEntries: 标记是否删除命名空间下所有缓存,默认为false
  • key: 同Cacheable注解,代表需要删除的命名空间下唯一的缓存key。
    例子中第一段,与 @Scheduled 注解同时使用,每十秒删除命名空间name下所有的缓存。
    第二段,调用此方法后删除命名空间models下, key == 参数 的缓存 
    同样含有unless与condition

3.@Caching注解可以让我们在一个方法或者类上同时指定多个Spring Cache相关的注解。其拥有三个属性:cacheable、put和evict,分别用于指定@Cacheable、@CachePut和@CacheEvict。
@Caching(cacheable = @Cacheable(“users”), evict = { @CacheEvict(“cache2”),
    @CacheEvict(value = “cache3”, allEntries = true) })

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值