Spring Cache Redis实现 (Spring Boot + Redis)
基于Spring Data Redis、Spring Cache实现后端缓存,提高并发。可实现 @Cacheable
有效期、固定时间过期。
环境
Spring Boot 2.1.7.RELEASE
前提
已经开启 Spring Cache
1
@EnableCaching
思路
- 自定义 redis 缓存管理
@Cacheable
指定缓存管理
实现
自定义 redis 缓存管理
1
2
3
4
5
6
7
8
9
10@Bean("customCacheManager")
public CacheManager commonCacheManager(RedisConnectionFactory redisConnectionFactory) {
// 设置缓存有效期5分钟
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration
.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(5L));
return RedisCacheManager
.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
.cacheDefaults(redisCacheConfiguration).build();
}@Cacheable
指定缓存管理1
2
3
4
5
6
7@Cacheable(
value = "redis:key:xxx",
cacheManager = "customCacheManager"
)
@RequestMapping(value = "index", method = RequestMethod.GET)
public ResponseEntity<IndexVO> index() {
...@CacheEvict 主动清理缓存
1
2
3
4
5
6
7@CacheEvict(
value = "redis:key:xxx",
cacheManager = "customCacheManager"
)
@RequestMapping(value = "index/clear", method = RequestMethod.GET)
public ResponseEntity clearIndex() {
...
案例
案例还有其他集成,本章读者可以直接阅读一下代码(跪求 Star……)
缓存管理
1
org.holy.spring.boot.quick.config.redis.RedisConfig#commonCacheManager
@Cacheable注解
1
org.holy.spring.boot.quick.controller.v1.IndexController#banner
@CacheEvict注解
1
org.holy.spring.boot.quick.controller.v1.IndexController#clearBanner
Spring Cache Redis实现 (Spring Boot + Redis)
http://example.com/2019/09/12/Spring-Cache-Redis实现-Spring-Boot-Redis/