You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpringBoot Redis配置entryTtl设置60秒过期不生效问题求助

问题根因及修复方案

你配置的RedisCacheManager仅对Spring Cache体系的@Cacheable/@CachePut/@CacheEvict注解生效,无法作用于使用@RedisHash注解的Spring Data Redis Repository实体,同时你的代码还存在3处可直接导致配置失效的语法/格式错误:

1. 修复Redis Repository实体TTL配置

给@RedisHash注解增加timeToLive属性,单位为秒,直接控制该类实体的默认过期时间:

// 60秒自动过期
@RedisHash(value = "rate", timeToLive = 60)
public class Rate implements Serializable  {
    // 原有代码保持不变
}

如果需要全局配置多个RedisHash实体的TTL,也可以自定义KeyspaceConfiguration注册到Spring容器,无需逐个实体加注解。

2. 修复Redis配置类语法错误

你现有配置类存在两处低级错误:

  • entryTtl配置行缺少右括号
  • RedisCacheConfiguration是不可变对象,调用usePrefix()后必须接收返回值才会生效
    修复后的redisCacheManager方法代码如下:
@Bean
public RedisCacheManager redisCacheManager(JedisConnectionFactory jedisConnectionFactory) {
    RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
            .disableCachingNullValues()
            // 补全右括号
            .entryTtl(Duration.ofSeconds(60))
            .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(RedisSerializer.json()));
    // 接收usePrefix返回的新配置对象
    redisCacheConfiguration = redisCacheConfiguration.usePrefix();
    return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(jedisConnectionFactory)
            .cacheDefaults(redisCacheConfiguration).build();
}

如果你的项目使用Spring Cache注解做缓存,还需要在配置类或启动类上加@EnableCaching注解开启缓存功能。

3. 修复yml配置缩进错误

yml靠层级缩进识别配置归属,你现有配置中cache、redis节点和spring平级,Spring无法读取到对应配置,修正后配置如下:

server:
  port: 8080
spring:
  cache:
    type: redis
  redis:
    host: localhost
    port: 6379

内容的提问来源于stack exchange,提问作者Anton Cavanaugh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 12:45:08