Spring Cache Redis实现 (Spring Boot + Redis)

基于Spring Data Redis、Spring Cache实现后端缓存,提高并发。可实现 @Cacheable有效期、固定时间过期。

环境

Spring Boot 2.1.7.RELEASE

前提

  1. 已经开启 Spring Cache

    1
    @EnableCaching

思路

  1. 自定义 redis 缓存管理
  2. @Cacheable 指定缓存管理

实现

  1. 自定义 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();
    }
  2. @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() {
    ...
  3. @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. 缓存管理

    1
    org.holy.spring.boot.quick.config.redis.RedisConfig#commonCacheManager
  2. @Cacheable注解

    1
    org.holy.spring.boot.quick.controller.v1.IndexController#banner
  3. @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/
作者
Holy
发布于
2019年9月12日
许可协议