引入相关包
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-redis', version: '2.0.4.RELEASE'
配置redis
- application.yml主要对应org.springframework.boot.autoconfigure.data.redis.RedisProperties
spring.redis.host=XXXX
spring.redis.port=6379
- 入口类启用缓存
@EnableCaching
使用缓存
- @Cacheable注解
优先查询缓存数据,没有再执行方法
- value(cacheNames)
缓存的方法名称,例如:cacheNames = “TEST_” - key
可以不制定,直接使用value值,支持SpEL 表达式,例如:key = “#id + ‘’” - unless
不缓存条件,当满足条件的时候不缓存数据,支持SpEL 表达式,例如:unless = “#result == null” - condition
缓存条件,与unless相反,当满足条件的时候缓存数据,支持SpEL 表达式,例如:unless = “#id != null” - keyGenerator
自定义缓存key生成器,与key属性互斥,如果不指定就使用默认key生成器。需要实现接口
org.springframework.cache.interceptor.KeyGenerator - cacheManager
与cacheResolver互斥,自定义缓存管理器。实现接口org.springframework.cache.CacheManager - cacheResolver
需要实现org.springframework.cache.interceptor.CacheResolver
- @CachePut注解
每次都会执行方法,并将结果存入指定的缓存中
- @CacheEvict注解
- allEntries
表示是否需要清除缓存中的所有元素。默认为false - beforeInvocation
是否在方法内容执行之前清除缓存,默认false。从来控制先清缓存还是后清缓存。
用来清除缓存
@Cacheable(cacheNames = "TEST_", key = "#id + ''", unless = "#result == null")
@Override
public RspDTO getCacheableUserInfo(Long id) {
logger.info("*****TestServiceImpl.getCacheableUserInfo参数id={}", id);
return new RspDTO(id);
}
@CachePut(cacheNames = "TEST_", key = "#id + ''", unless = "#result == null")
@Override
public RspDTO getCachePutUserInfo(Long id) {
logger.info("*****TestServiceImpl.getCachePutUserInfo参数id={}", id);
return new RspDTO(id);
}
@CacheEvict(cacheNames = "TEST_", key = "#id + ''")
@Override
public boolean delete(Long id) {
logger.info("*****TestServiceImpl.delete参数id={}", id);
return true;
}
- @CacheConfig注解
是一个类级别的注解,允许共享缓存的名称、KeyGenerator、CacheManager 和CacheResolver。 同时如果方法制定了自己的属性,可以 覆盖该注解中的属性。
- @Caching注解
可以做一些复杂的操作,当@CacheEvict或者@CachePut单一注解无法实现的时候
@Caching(
cacheable = {@Cacheable(key = "#id + ''", unless = "#result == null")},
put = {@CachePut(key = "#id + ''", unless = "#result == null")},
evict = {@CacheEvict(key = "#id + ''")}
)
源码位置
https://gitee.com/ceclar123/spring-boot-demo/tree/master/ch02