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

引入spring-data-redis后Spring缓存误调用RedisCache.put()导致序列化报错

解决方案

以下三种方案均可实现需求,按需选择即可:

  • 方案1:配置文件指定缓存类型(操作最简单)
    在项目配置文件中强制指定缓存类型,Spring缓存模块会优先使用指定的实现,完全不影响Redis Streams相关功能:
    若使用application.properties:

    spring.cache.type=simple
    

    若使用application.yml:

    spring:
      cache:
        type: simple
    

    这里的simple对应Spring Boot默认的内存缓存实现,如果你此前使用的是其他缓存(如Caffeine、Ehcache等),替换为对应类型值即可。

  • 方案2:排除Redis缓存专属自动配置
    在启动类注解中排除Redis缓存的自动配置类,仅禁用Redis作为缓存载体的能力,Redis的其他核心功能(包括Redis Streams、RedisTemplate等)均正常加载:

    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.autoconfigure.cache.RedisCacheAutoConfiguration;
    
    @SpringBootApplication(exclude = RedisCacheAutoConfiguration.class)
    public class YourApplication {
        public static void main(String[] args) {
            SpringApplication.run(YourApplication.class, args);
        }
    }
    
  • 方案3:显式声明自定义缓存管理器
    如果你有自定义缓存规则的需求,直接将你需要的CacheManager实现注册为Bean并添加@Primary注解,优先级会高于自动装配的RedisCacheManager:

    import org.springframework.cache.CacheManager;
    import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Primary;
    
    @Configuration
    public class CacheConfig {
        @Bean
        @Primary
        public CacheManager cacheManager() {
            // 这里返回你实际使用的缓存管理器实现即可
            return new ConcurrentMapCacheManager();
        }
    }
    

根因说明

Spring Boot缓存自动配置会按依赖优先级选择缓存实现,引入spring-data-redis后RedisCache优先级高于默认内存缓存,因此缓存自动切换为Redis实现。RedisCache默认使用JDK序列化,要求缓存对象实现Serializable接口,而内存缓存无序列化要求,因此触发序列化异常。上述方案均从根源绕过Redis作为缓存的逻辑,无需修改原有缓存业务,也无需为缓存对象额外添加序列化实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 15:36:02