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

如何验证Spring Redis缓存是否正常工作及排查缓存失效问题

Spring Redis缓存不生效的问题排查与修复

以下是你的配置和代码中遗漏的关键点及修复方案:

1. 未开启Spring缓存功能

Spring的注解式缓存(如@Cacheable)需要通过@EnableCaching注解开启,否则所有缓存注解都会被忽略。

修复:在缓存配置类或Spring Boot启动类上添加@EnableCaching:

@Getter
@Setter
@Configuration
@EnableCaching // 添加该注解开启缓存功能
@ConfigurationProperties(prefix = "my-service.redis")
@ConditionalOnProperty(value = "spring.cache.type", havingValue = "redis")
public class MyServiceCacheConfiguration {
    // ... 原有代码
}

2. @Cacheable缺少必填的缓存名称属性

@Cacheable必须指定value或cacheNames属性,用于标识缓存实例的名称,Spring需要该属性定位对应的缓存存储空间。

修复:给findKeyword方法的@Cacheable添加cacheNames属性:

@Cacheable(cacheNames = "keywordCache", key = "#application.concat('::').concat(#label).concat('::').concat(#locale)")
public Keyword findKeyword(String application, String label, LocaleEnum locale){
    // ... 原有代码
}

3. 配置类中未定义常量(编译错误隐患)

你的配置类中使用了HOST、PORT等常量但未给出定义,这会导致编译错误。需要补充常量定义:

@Getter
@Setter
@Configuration
@EnableCaching
@ConfigurationProperties(prefix = "my-service.redis")
@ConditionalOnProperty(value = "spring.cache.type", havingValue = "redis")
public class MyServiceCacheConfiguration {
    // 补充常量定义
    private static final String HOST = "hostname";
    private static final String PORT = "port";
    private static final String USERNAME = "username";
    private static final String PASSWORD = "password";
    private static final String CONNECTION_POOL_SIZE = "connectionPoolSize";
    private static final String RETRY_ATTEMPTS = "retryAttempts";
    private static final String MINIMUM_IDLE_CONNECTIONS = "minimumIdleConnections";
    private static final String CONNECTION_TIMEOUT = "connectionTimeout";
    private static final String IDLE_TIMEOUT = "idleTimeout";
    
    // ... 原有代码
}

4. 确保方法所在类是Spring Bean

findKeyword方法所在的类必须被Spring容器管理(添加@Service、@Component等注解),否则Spring无法为其创建代理类,缓存注解无法生效。

示例:

@Service // 标记类为Spring Bean
public class KeywordService {
    // ... 其他代码
    @Cacheable(cacheNames = "keywordCache", key = "#application.concat('::').concat(#label).concat('::').concat(#locale)")
    public Keyword findKeyword(String application, String label, LocaleEnum locale){
        // ... 原有代码
    }
}

5. 可选:配置Redisson缓存的默认规则

当前RedissonSpringCacheManager传入的是空配置Map,可添加缓存过期时间等规则,提升缓存实用性:

@Bean
CacheManager cacheManager(@Qualifier("redissonCacheClient") RedissonClient redissonClient) {
    LOG.info("Creating cache manager");
    Map<String, CacheConfig> config = new HashMap<>();
    // 为keywordCache设置1小时过期时间,30分钟空闲淘汰时间
    config.put("keywordCache", new CacheConfig(3600000, 1800000));
    return new RedissonSpringCacheManager(redissonClient, config);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 14:30:00