说明
spring cache是spring框架的缓存抽象,集成了各种主流缓存实现(ConcurrentMap、redis、ehcache、Caffeine等)
spring默认使用ConcurrentMap作为缓存;如果工程中引入了redis配置,则会使用redis作为缓存
spring通过CacheManager判断具体使用哪个缓存,每个缓存都有一个具体的CacheManager(比如:EhCacheCacheManager,RedisCacheManager,CaffeineCacheManager),如果没有配置任何的CacheManager,则会使用ConcurrentMap作为缓存
常用注解说明
名称 | 说明 |
---|---|
@EnableCaching | 开启基于注解的缓存 |
@CacheConfig | 统一配置本类的缓存注解的属性 |
@Cacheable | 常用于查询方法,能够根据方法的请求参数对其进行缓存 |
@CachePut | 常用于更新/保存方法,会将方法返回值放入缓存 |
@CacheEvict | 清空缓存 |
SpEL表达式说明
注解中key的写法是SpEL表达式,
Spring Cache提供了一些供我们使用的SpEL上下文数据,下表直接摘自Spring官方文档:
名称 | 位置 | 描述 | 示例 |
---|---|---|---|
methodName | root | 当前被调用的方法名 | #root.methodname |
method | root | 当前被调用的方法 | #root.method.name |
target | root | 当前被调用的目标对象实例 | #root.target |
targetClass | root | 当前被调用的目标对象的类 | #root.targetClass |
args | root | 方法的参数列表 | #root.args[0] |
caches | root | 当前方法调用使用的缓存列表 | #root.caches[0].name |
Argument Name | 执行上下文 | 当前被调用的方法的参数,如findArtisan(Artisan artisan),可以通过#artsian.id获得参数 | #artsian.id |
result | 执行上下文 | 方法执行后的返回值(仅当方法执行后的判断有效,如 unless cacheEvict的beforeInvocation=false) | #result |
说明:
1、当我们要使用root对象的属性作为key时我们也可以将“#root”省略,因为Spring默认使用的就是root对象的属性。如:
@Cacheable(key = "targetClass + methodName +#p0")
2、使用方法参数时我们可以直接使用“#参数名”或者“#p参数index”。如:
@Cacheable(value="users", key="#id")
@Cacheable(value="users", key="#p0")
SpEL提供了多种运算符
类型 | 运算符 |
---|---|
关系 | <,>,<=,>=,==,!=,lt,gt,le,ge,eq,ne |
算术 | +,- ,* ,/,%,^ |
逻辑 | &&, |
条件 | ?: (ternary),?: (elvis) |
正则表达式 | matches |
其他类型 | ?.,?[…],![…],$[…],^[…] |
在工程中使用
1、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
2、在工程中配置
在启动类中增加注解 @EnableCaching 开启缓存功能
在application.properties中添加可选自定义配置
配置项 | 说明 | 示例 |
---|---|---|
spring.cache.type | 缓存类型(redis、caffeine、simple、none等) | redis |
spring.cache.cache-names | 缓存名称,逗号隔开 | cache1,cache2 |
spring.cache.redis.time-to-live | redis缓存有效期(毫秒) | 600000 |
详细配置项可参考(org.springframework.boot.autoconfigure.cache.CacheProperties)
3、在代码中使用
1)保存时,缓存返回值
@CachePut(value="dict",key="targetClass +'AppDictType'+ #entity.dictTypeCd")
@Transactional(readOnly = false)
public AppDictType save(AppDictType entity) {
return dictTypeDao.save(entity);
}
2)查询时,先读取缓存,如果缓存不存在,则执行方法查询,然后更新缓存
@Cacheable(value="dict",key="targetClass +'AppDictType'+ #dictTypeCd")
public AppDictType findByDictTypeCd(String dictTypeCd) {
return dictTypeDao.findByDictTypeCd(dictTypeCd);
}
3)删除时,清空缓存
@Transactional(readOnly = false)
@CacheEvict(value="dict",key="targetClass +'AppDictType'+ #dictTypeCd")
public void deleteByDictTypeCd(String dictTypeCd) {
dictTypeDao.deleteByDictTypeCd(dictTypeCd);
}
4)测试用例
@Test
public void testCache() {
String dictTypeCd = "test01";
AppDictType entity = new AppDictType();
entity.setDictTypeCd(dictTypeCd);
entity.setDictTypeName("测试01");
// 新增记录,并放入缓存
entity = dictService.save(entity);
// 查询缓存
AppDictType dict = dictService.findByDictTypeCd(dictTypeCd);
logger.info("dict1:{}", JsonUtil.obj2Json(dict));
// 修改数据
entity.setDictTypeName("测试0011");
entity = dictService.save(entity);
// 查询缓存,数据发生变化
AppDictType dict2 = dictService.findByDictTypeCd(dictTypeCd);
logger.info("dict2:{}", JsonUtil.obj2Json(dict3));
// 删除记录,并清除缓存
dictService.deleteByDictTypeCd(dictTypeCd);
// 查询记录为空
AppDictType dict3 = dictService.findByDictTypeCd(dictTypeCd);
logger.info("dict3:{}", JsonUtil.obj2Json(dict4));
}
4、使用redis缓存
1)引入redis依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2)在application.properties 配置redis链接参数
spring.redis.host=192.168.1.144
spring.redis.port=6379
5、关闭spring cache缓存
如果已经开启了@EnableCaching缓存,在某些环境下又不想使用缓存,又不想修改原有代码。
可通过如下配置关闭缓存:
spring.cache.type=none
参考
- https://www.cnblogs.com/yueshutong/p/9381540.html
- https://docs.spring.io/spring-boot/docs/2.2.0.RELEASE/reference/htmlsingle/#boot-features-caching