SpringCache常⽤注解详解Spring Cache常⽤注解详解
@EnableCaching
开启Spring Cache框架⽀持。解析对应的注解,实现缓存读写访问
@CacheConfig
缓存配置,可以配置当前类型中所⽤缓存注解的通⽤信息
⽰例:配置当类前所有缓存注解的缓存前缀
@CacheConfig(cacheNames ="cache:prefix")
@Cacheable
表⽰要对⽅法返回值进⾏缓存
注解属性:
cacheNames : 缓存key前缀名字
key :缓存key后缀
condition : SpringEL表达式,结果为true,缓存数据到redis。结果为false,不缓存数据到redis。
unless:SpringEL表达式,结果为false,缓存数据到redis。结果为true,不缓存数据到redis。⽰例
//执⾏⽅法时,返回结果做缓存
@Cacheable(cacheNames="cache:prefix",key ="'all:values'")
//⽅法参数id 作为key的⼀部分,做缓存
@CachePut(key ="'TestServiceImpl:getById:'+#id")
el表达式执行结果为//⽅法参数id 作为key的⼀部分,做缓存,⽅法返回结果为null时,不做缓存
@Cacheable(key ="'testUnless('+#id+')'",unless ="#result==null")
//⽅法参数id⼤于0时作为key的⼀部分,做缓存
@Cacheable(key ="'TestServiceImpl:getById:'+#id", condition ="#id > 0")
@CacheEvict
淘汰缓存注解
注解属性:
allEntries 代表是否删除cacheNames对应的全部的缓存。 ,默认false,可选true。
注解属性和Cacheable相似
⽰例
//执⾏⽅法时,根据key删除缓存
@CacheEvict(allEntries =true)
@CachePut
更新缓存,如果key存在覆盖缓存数据。key不存在,新增数据到缓存。
注解属性:跟@Cacheable相似
⽰例
//⽅法参数id 作为key的⼀部分,根据key更新缓存
@CachePut(key ="'TestServiceImpl:getById:'+#id")

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。