Springboot @Cacheable自定义缓存过期时间

pom

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>

yml

#  redis配置
spring:
    redis:
      database: 0
      host: 127.0.0.1
      password: 123456
      port: 6379
      timeout:  5000
      lettuce:
        pool:
          max-active: 300
          max-wait: -1
          max-idle: 20
          min-idle: 10

RedisConfig

RedisCacheManager:

RedisCacheManager缓存默认不过期,所以这里返回自定RedisCacheManager

//return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
return new CustomRedisCacheManager(redisCacheWriter, redisCacheConfiguration);
@Configuration
public class RedisConfig {
    
    /*
     * @description redis序列化方式
     * @author xianping
     * @date 2020/9/25
     * @param redisConnectionFactory
     * @return RedisTemplate
     **/
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    /*
     * @description Redis缓存的序列化方式使用redisTemplate.getValueSerializer(),不在使用JDK默认的序列化方式
     * @author xianping
     * @date 2020/9/25
     * @param redisTemplate
     * @return RedisCacheManager
     **/
    @Bean
    public RedisCacheManager redisCacheManager(RedisTemplate redisTemplate) {
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisTemplate.getConnectionFactory());
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()               
        .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getValueSerializer()));
        //return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
        return new CustomRedisCacheManager(redisCacheWriter, redisCacheConfiguration);
    }
}

CustomRedisCacheManager

自定义RedisCacheManager:若@Cacheable value中包含’#‘号,则’#'后为缓存生存时间,不存在则表示缓存不进行生存时间设置

//cacheConfig.entryTtl 设置缓存过期时间
public RedisCacheConfiguration entryTtl(Duration ttl) {
    Assert.notNull(ttl, "TTL duration must not be null!");
    return new RedisCacheConfiguration(ttl, this.cacheNullValues, this.usePrefix, 			this.keyPrefix, this.keySerializationPair, this.valueSerializationPair, 				this.conversionService);
}
//Duration.ofMinutes 持续时间
//这里默认是以分钟为单位,所以调用ofMinutes静态方法进行转换
public static Duration ofMinutes(long minutes) {
        return create(Math.multiplyExact(minutes, SECONDS_PER_MINUTE), 0);
}
public class CustomRedisCacheManager extends RedisCacheManager {

    /*
     * @description 提供默认构造器
     * @author xianping
     * @date 2020/9/28 9:22
     * @param
     * @param cacheWriter
     * @param defaultCacheConfiguration
     * @return
     **/
    public CustomRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
        super(cacheWriter, defaultCacheConfiguration);
    }

    /*
     * @description 重写父类createRedisCache方法
     * @author xianping
     * @date 2020/9/28 9:22
     * @param
     * @param name @Cacheable中的value
     * @param cacheConfig
     * @return org.springframework.data.redis.cache.RedisCache
     **/
    @Override
    protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {
        //名称中存在#标记进行到期时间配置
        if (!name.isEmpty() && name.contains("#")) {
            String[] SPEL = name.split("#");
            if (StringUtils.isNumeric(SPEL[1])) {
                //配置缓存到期时间
                int cycle = Integer.parseInt(SPEL[1]);
                return super.createRedisCache(SPEL[0], cacheConfig.entryTtl(Duration.ofMinutes(cycle * 24 * 60)));
            }
        }
        return super.createRedisCache(name, cacheConfig);
    }
}

使用

生存时间1天

@Cacheable(value = "cacheTest#1")
public String cacheTest() {
    return "cacheTest";
}

缓存持久,无过期时间

@Cacheable(value = "cacheTest")
public String cacheTest() {
    return "cacheTest";
}
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值