spring cache缓存框架使用

说明

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官方文档:

名称位置描述示例
methodNameroot当前被调用的方法名#root.methodname
methodroot当前被调用的方法#root.method.name
targetroot当前被调用的目标对象实例#root.target
targetClassroot当前被调用的目标对象的类#root.targetClass
argsroot方法的参数列表#root.args[0]
cachesroot当前方法调用使用的缓存列表#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-liveredis缓存有效期(毫秒)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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

顽石九变

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值