引入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
相关产品推荐
相关产品推荐

