全网整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:400-708-3566

详解Spring缓存注解@Cacheable,@CachePut , @CacheEvict使用

注释介绍

@Cacheable

@Cacheable 的作用 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存

@Cacheable 作用和配置方法

参数解释example
value缓存的名称,在 spring 配置文件中定义,必须指定至少一个例如:
@Cacheable(value=”mycache”)
@Cacheable(value={”cache1”,”cache2”}
key缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合@Cacheable(value=”testcache”,key=”#userName”)
condition缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存@Cacheable(value=”testcache”,condition=”#userName.length()>2”)

实例

@Cacheable(value=”accountCache”),这个注释的意思是,当调用这个方法的时候,会从一个名叫 accountCache 的缓存中查询,如果没有,则执行实际的方法(即查询数据库),并将执行的结果存入缓存中,否则返回缓存中的对象。这里的缓存中的 key 就是参数 userName,value 就是 Account 对象。“accountCache”缓存是在 spring*.xml 中定义的名称。

@Cacheable(value="accountCache")// 使用了一个缓存名叫 accountCache 
public Account getAccountByName(String userName) {
   // 方法内部实现不考虑缓存逻辑,直接实现业务
   System.out.println("real query account."+userName); 
   return getFromDB(userName); 
} 

@CachePut

@CachePut 的作用 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存,和 @Cacheable 不同的是,它每次都会触发真实方法的调用

@CachePut 作用和配置方法

参数解释example
value缓存的名称,在 spring 配置文件中定义,必须指定至少一个@CachePut(value=”my cache”)
key缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合@CachePut(value=”testcache”,key=”#userName”)
condition缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存@CachePut(value=”testcache”,condition=”#userName.length()>2”)

实例

@CachePut 注释,这个注释可以确保方法被执行,同时方法的返回值也被记录到缓存中,实现缓存与数据库的同步更新。

@CachePut(value="accountCache",key="#account.getName()")// 更新accountCache 缓存
public Account updateAccount(Account account) { 
  return updateDB(account); 
} 

@CacheEvict

@CachEvict 的作用 主要针对方法配置,能够根据一定的条件对缓存进行清空

@CacheEvict 作用和配置方法

参数解释example
value缓存的名称,在 spring 配置文件中定义,必须指定至少一个@CacheEvict(value=”my cache”)
key缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写,如果不指定,则缺省按照方法的所有参数进行组合@CacheEvict(value=”testcache”,key=”#userName”)
condition缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false,只有为 true 才进行缓存@CacheEvict(value=”testcache”,condition=”#userName.length()>2”)
allEntries是否清空所有缓存内容,缺省为 false,如果指定为 true,则方法调用后将立即清空所有缓存@CachEvict(value=”testcache”,allEntries=true)
beforeInvocation是否在方法执行前就清空,缺省为 false,如果指定为 true,则在方法还没有执行的时候就清空缓存,缺省情况下,如果方法执行抛出异常,则不会清空缓存@CachEvict(value=”testcache”,beforeInvocation=true)

实例

@CacheEvict(value="accountCache",key="#account.getName()")// 清空accountCache 缓存 
public void updateAccount(Account account) {
   updateDB(account); 
} 

@CacheEvict(value="accountCache",allEntries=true)// 清空accountCache 缓存
public void reload() {
   reloadAll()
}

@Cacheable(value="accountCache",condition="#userName.length() <=4")// 缓存名叫 accountCache 
public Account getAccountByName(String userName) { 
 // 方法内部实现不考虑缓存逻辑,直接实现业务
 return getFromDB(userName); 
}

@CacheConfig

所有的@Cacheable()里面都有一个value=“xxx”的属性,这显然如果方法多了,写起来也是挺累的,如果可以一次性声明完 那就省事了, 所以,有了@CacheConfig这个配置,@CacheConfig is a class-level annotation that allows to share the cache names,如果你在你的方法写别的名字,那么依然以方法的名字为准。

@CacheConfig("books")
public class BookRepositoryImpl implements BookRepository {

  @Cacheable
  public Book findBook(ISBN isbn) {...}
}

条件缓存

下面提供一些常用的条件缓存

//@Cacheable将在执行方法之前( #result还拿不到返回值)判断condition,如果返回true,则查缓存; 
@Cacheable(value = "user", key = "#id", condition = "#id lt 10")
public User conditionFindById(final Long id) 

//@CachePut将在执行完方法后(#result就能拿到返回值了)判断condition,如果返回true,则放入缓存; 
@CachePut(value = "user", key = "#id", condition = "#result.username ne 'zhang'") 
public User conditionSave(final User user)  

//@CachePut将在执行完方法后(#result就能拿到返回值了)判断unless,如果返回false,则放入缓存;(即跟condition相反)
@CachePut(value = "user", key = "#user.id", unless = "#result.username eq 'zhang'")
public User conditionSave2(final User user)  

//@CacheEvict, beforeInvocation=false表示在方法执行之后调用(#result能拿到返回值了);且判断condition,如果返回true,则移除缓存;
@CacheEvict(value = "user", key = "#user.id", beforeInvocation = false, condition = "#result.username ne 'zhang'") 
public User conditionDelete(final User user)  

@Caching

有时候我们可能组合多个Cache注解使用;比如用户新增成功后,我们要添加id–>user;username—>user;email—>user的缓存;此时就需要@Caching组合多个注解标签了。

@Caching(put = {
@CachePut(value = "user", key = "#user.id"),
@CachePut(value = "user", key = "#user.username"),
@CachePut(value = "user", key = "#user.email")
})
public User save(User user) {

自定义缓存注解

比如之前的那个@Caching组合,会让方法上的注解显得整个代码比较乱,此时可以使用自定义注解把这些注解组合到一个注解中,如:

@Caching(put = {
@CachePut(value = "user", key = "#user.id"),
@CachePut(value = "user", key = "#user.username"),
@CachePut(value = "user", key = "#user.email")
})
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface UserSaveCache {
}

这样我们在方法上使用如下代码即可,整个代码显得比较干净。

@UserSaveCache
public User save(User user)

扩展

比如findByUsername时,不应该只放username–>user,应该连同id—>user和email—>user一起放入;这样下次如果按照id查找直接从缓存中就命中了

@Caching(
  cacheable = {
    @Cacheable(value = "user", key = "#username")
  },
  put = {
    @CachePut(value = "user", key = "#result.id", condition = "#result != null"),
    @CachePut(value = "user", key = "#result.email", condition = "#result != null")
  }
)
public User findByUsername(final String username) {
  System.out.println("cache miss, invoke find by username, username:" + username);
  for (User user : users) {
    if (user.getUsername().equals(username)) {
      return user;
    }
  }
  return null;
}

其实对于:id—>user;username—->user;email—>user;更好的方式可能是:id—>user;username—>id;email—>id;保证user只存一份;如:

@CachePut(value="cacheName", key="#user.username", cacheValue="#user.username") 
public void save(User user)  


@Cacheable(value="cacheName", key="#user.username", cacheValue="#caches[0].get(#caches[0].get(#username).get())") 
public User findByUsername(String username) 

SpEL上下文数据

Spring Cache提供了一些供我们使用的SpEL上下文数据,下表直接摘自Spring官方文档:

名称位置描述示例
methodNameroot对象当前被调用的方法名root.methodName
methodroot对象当前被调用的方法root.method.name
targetroot对象当前被调用的目标对象root.target
targetClassroot对象当前被调用的目标对象类root.targetClass
argsroot对象当前被调用的方法的参数列表root.args[0]
cachesroot对象当前方法调用使用的缓存列表(如@Cacheable(value={“cache1”, “cache2”})),则有两个cacheroot.caches[0].name
argument name执行上下文当前被调用的方法的参数,如findById(Long id),我们可以通过#id拿到参数user.id
result执行上下文方法执行后的返回值(仅当方法执行之后的判断有效,如‘unless’,’cache evict’的beforeInvocation=false)result
@CacheEvict(value = "user", key = "#user.id", condition = "#root.target.canCache() and #root.caches[0].get(#user.id).get().username ne #user.username", beforeInvocation = true) 
public void conditionUpdate(User user) 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


# spring cache 注解  # spring cacheable  # spring cacheput  # Spring Boot 缓存注解@Cacheable、@CachePut、@Ca  # SpringBoot中的@CacheEvict 注解的实现  # 详解Spring数据缓存注解@Cacheable、@CachePut、@CacheEvict  # Springboot Cache @CacheEvict 无法模糊删除  # spring整合redis缓存并以注解(@Cacheable、@CachePut、@CacheEvi  # Spring全家桶中@CacheEvict无效情况的问题解决  # 清空  # 为空  # 返回值  # 将在  # 配置文件  # 就能  # 多个  # 对其  # 自定义  # 的是  # 是在  # 都有  # 还没有  # 那就  # 你在  # 我们可以  # 并将  # 如果没有  # 会让  # 可以使用 


相关文章: 广州顶尖建站服务:企业官网建设与SEO优化一体化方案  七夕网站制作视频,七夕大促活动怎么报名?  如何用y主机助手快速搭建网站?  官网自助建站系统:SEO优化+多语言支持,快速搭建专业网站  如何通过万网虚拟主机快速搭建网站?  如何用PHP快速搭建高效网站?分步指南  广东企业建站网站优化与SEO营销核心策略指南  c++23 std::expected怎么用 c++优雅处理函数错误返回【详解】  如何获取免费开源的自助建站系统源码?  官网网站制作腾讯审核要多久,联想路由器newifi官网  大连网站制作公司哪家好一点,大连买房网站哪个好?  如何在云指建站中生成FTP站点?  头像制作网站在线观看,除了站酷,还有哪些比较好的设计网站?  详解ASP.NET 生成二维码实例(采用ThoughtWorks.QRCode和QrCode.Net两种方式)  建站之星安装失败:服务器环境不兼容?  视频网站制作教程,怎么样制作优酷网的小视频?  已有域名能否直接搭建网站?  建站之星导航菜单设置与功能模块配置全攻略  建站VPS配置与SEO优化指南:关键词排名提升策略  油猴 教程,油猴搜脚本为什么会网页无法显示?  如何快速搭建高效WAP手机网站吸引移动用户?  电商网站制作价格怎么算,网上拍卖流程以及规则?  小建面朝正北,A点实际方位是否存在偏差?  建站之星如何助力网站排名飙升?揭秘高效技巧  建站主机服务器选型指南与性能优化方案解析  子杰智能建站系统|零代码开发与AI生成SEO优化指南  如何用免费手机建站系统零基础打造专业网站?  矢量图网站制作软件,用千图网的一张矢量图做公司app首页,该网站并未说明版权等问题,这样做算不算侵权?应该如何解决?  h5在线制作网站电脑版下载,h5网页制作软件?  天津个人网站制作公司,天津网约车驾驶员从业资格证官网?  昆明网站制作哪家好,昆明公租房申请网上登录入口?  我的世界制作壁纸网站下载,手机怎么换我的世界壁纸?  制作充值网站的软件,做人力招聘为什么要自己交端口钱?  武汉网站如何制作,黄黄高铁武穴北站途经哪些村庄?  网站制作培训多少钱一个月,网站优化seo培训课程有哪些?  用v-html解决Vue.js渲染中html标签不被解析的问题  香港服务器网站卡顿?如何解决网络延迟与负载问题?  建站主机空间推荐 高性价比配置与快速部署方案解析  如何做网站制作流程,*游戏网站怎么搭建?  模具网站制作流程,如何找模具客户?  如何通过可视化优化提升建站效果?  建站之星安装后如何配置SEO及设计样式?  网站建设设计制作营销公司南阳,如何策划设计和建设网站?  Android自定义控件实现温度旋转按钮效果  临沂网站制作企业,临沂第三中学官方网站?  公司门户网站制作流程,华为官网怎么做?  微信小程序 input输入框控件详解及实例(多种示例)  北京专业网站制作设计师招聘,北京白云观官方网站?  建站ABC备案流程中有哪些关键注意事项?  小程序网站制作需要准备什么资料,如何制作小程序? 

您的项目需求

*请认真填写需求信息,我们会在24小时内与您取得联系。