Spring使用redis做缓存在一个方法上使用注解操作多个缓存

我们使用的最基础的Spring缓存注解如下:

    @Cacheable   生成缓存   一般用在查询Service接口上

    @Cacheable(value={"users"}, key=" #root.methodName + #user.id", condition="#user.id%2==0")

      public User find(User user) {

           System.out.println("find user by user " + user);

            return user;

       }

   key绑定方法接受的参数,根据参数的不同会生存相应不同的缓存。

   condition为缓存触发条件,满足此条件才会触发缓存,不写默认缓存所有。

 

@CacheEvict  删除缓存  一般用在增删改的Service接口上,保证数据库数据和缓存的同步

 @CacheEvict(value="users", key = " '自定义字符串'+ #id"  ,allEntries=false)

   public void delete(Integer id) {

      System.out.println("delete user by id: " + id);

   }

 allEntries=true 这个属性直接删除由values外层键下面的所有缓存

 

@Caching注解可以让我们在一个方法或者类上同时指定多个Spring Cache相关的注解。其拥有三个属性:cacheable、put和evict,分别用于指定@Cacheable、@CachePut和@CacheEvict。

   @Caching(cacheable = @Cacheable("users"), evict = { @CacheEvict("cache2"),

         @CacheEvict(value = "cache3", allEntries = true) })

   public User find(Integer id) {

      returnnull;

   }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值