Spring Cache 缓存优化
Spring Cache介绍:
是一个框架,实现接口,基于注解的缓存功能。
Spring Cache — CacheManager是Spring提供的各种缓存技术的抽象接口(默认有个Map缓存)
redis 实现CacheManager — redisCacheManager根据redis实现缓存
mongo 实现CacheManager — mongoCacheManager根据mongo实现缓存
Spring Cache的常用注解:
- @EnableCaching开启缓存注解功能
- @Cacheable在方法执行前spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中
- @CachePut将方法的返回值放到缓存中
- @CacheEvict将一条或多条数据从缓存中删除
@EnableCaching:
添加到启动类上开启Spring Cache缓存注解功能
@CachePut:
如果不使用第三方缓存,默认使用的是ConcurrentHeahMap缓存数据
- @CachePut(value = "userCache ",key = " #result.id ")
作用: 将方法返回值,放入缓存
#result.id返回值的id做key(spel表达式)
value: 缓存的名称, 每个缓存名称下面可以有很多key
key: 缓存的key ----------> 支持Spring的表达式语言SPEL语法
key的写法有:
#user.id : #user指的是方法形参的名称, id指的是user的id属性 , 也就是使用user的id属性作为key ;
#result.id : #result代表方法返回值,该表达式 代表以返回对象的id属性作为key ;
@CacheEvict:
作用: 清理指定缓存
- @CacheEvict(value = “userCache”,key = “#id”)
- @CacheEvict(value = “userCache”,allEntries = ture)
value: 缓存的名称,每个缓存名称下面可以有多个key
key: 缓存的key ----------> 支持Spring的表达式语言SPEL语法 ,allEntries = ture清除所有缓存
key的写法有:
@CacheEvict(value = “userCache”,key = “#p0.id”) //#p0 代表形参第一个参数的id属性
@CacheEvict(value = “userCache”,key = “#root.args[0]”) //#root.args[0] 代表形参第一个参数
@CacheEvict(value = “userCache”,key = “#id”) //#id 代表形参变量名为id的参数
@Cacheable:
作用: 在方法执行前,spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中
- @Cacheable(value = “userCache”,key = “#id”)
value: 缓存的名称,每个缓存名称下面可以有多个key key: 缓存的key ----------> 支持Spring的表达式语言SPEL语法
在@Cacheable注解中,提供了两个属性分别为: condition, unless 。
- @Cacheable(value = “userCache”,key = “#id”, unless = “#result ==null”)
condition : 表示满足什么条件, 再进行缓存 (当是redis不能使用);
unless : 表示满足条件则不缓存 ; 与上述的condition是反向的 ; 实现redis
@Cacheable(value = "userCache",key = "#user.id + '_' + #user.name")
多个参数的可以使用'_'进行拼接
1.pom.xml依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.application.yml
spring:
redis:
host: 192.168.200.200
port: 6379
password: root@123456
database: 0
cache:
redis:
time-to-live: 1800000 #设置缓存过期时间,可选