spring-boot - Redis 无法反序列化对象
问题描述
我已将 Redis 缓存添加到我的项目中,并且缓存本身可以工作,但是加载缓存的值失败,并出现以下异常:
java.lang.ClassCastException: class com.dto.FilterOptionsDto cannot be cast to class
com.dto.FilterOptionsDto (com.dto.FilterOptionsDto is in unnamed module of loader 'app';
com.dto.FilterOptionsDto is in unnamed module of loader org.springframework.boot.devtools.restart.classloader.RestartClassLoader @3d0da857)
at ....
缓存配置
@Configuration
@EnableConfigurationProperties({CacheProperties.class})
public class RedisConfig {
@Bean
RedisCacheManagerBuilderCustomizer redisCacheManagerBuilderCustomizer(CacheProperties cacheProperties) {
return builder -> {
Map<String, RedisCacheConfiguration> configurationMap = new HashMap<>();
configurationMap.put(CacheNames.IDP_USER_PROFILES, RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(cacheProperties.getIdpUserProfilesTtlSeconds())));
configurationMap.put(CacheNames.STIBO_STORES_FILTER_OPTIONS, RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(cacheProperties.getIdpUserProfilesTtlSeconds())));
builder.withInitialCacheConfigurations(configurationMap);
};
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(new LettuceConnectionFactory());
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return redisTemplate;
}
}
缓存使用情况
@Override
@Cacheable(value = CacheNames.STIBO_STORES_FILTER_OPTIONS)
public FilterOptionsDto getStoresFilterOptions(CountryEnum country, boolean includeClosedStores, boolean includeSingleOptions) {
注意:FilterOptionsDto
实现可序列化。我发现序列化的值被保存到 redis db,但是每当 spring 尝试反序列化它时,它都会失败。
类似问题:Problem in deserialize redis-cache to objects in Spring-boot
解决方案
解决方案很奇怪,但很简单 - 删除devtools
依赖项。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
推荐阅读
- c++ - 将 char[] 数组转换为字节,然后将字节转换为 int,反之亦然
- javascript - 无论如何要更改错误代码“TypeError:a未定义”?
- nginx - Nginx 405 方法不允许,即使是 JSON 响应
- c++ - 我需要做一个深拷贝,我是否正确使用了我的复制构造函数?
- c++ - 如何在 C++11 的内存池中分配 std::map 的内部 RB_tree 节点?
- android - 在 onCreate 开始时使用 setText 无法更改我的 textView 的文本
- javascript - 根据变量的长度多次进行突变调用
- google-cloud-platform - Google Cloud 分层计费 - 项目 v 计费帐户
- python - 在 numpy 数组中查找最近的值
- jenkins - 如何在我的代码中引用 jenkinsfile 声明性工具参考