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")
//方法参数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")