我一直在尝试更改 spring-boot redis 缓存的默认序列化程序,因为我想从 Default 更改为 Jackson2Json 实现之一。Jackson2Json 库中有两个实现,其中之一是:GenericJackson2JsonRedisSerializer,我可以在以下 bean 实例化中使用它:
@Bean
@Primary
public RedisCacheConfiguration defaultCacheConfig(ObjectMapper objectMapper) {
return RedisCacheConfiguration.defaultCacheConfig()
.serializeKeysWith(
SerializationPair.fromSerializer(
new StringRedisSerializer()
)
)
.serializeValuesWith(
SerializationPair.fromSerializer(
new GenericJackson2JsonRedisSerializer(objectMapper)
)
)
.prefixKeysWith("");
}
当我使用此序列化程序时,序列化工作正常,所有内容都存储在 redis 服务器上,但是当我尝试反序列化存储在 redis 服务器上的 JSON 时,我收到以下异常:
java.util.LinkedHashMap cannot be cast to tutorial.Person with root cause
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to tutorial.Person
缓存的使用方式如下:
@Cacheable(cacheNames = "person", key = "'person:'.concat(#post.id)")
public Person findPostAuthor(Post post){
}
序列化程序不知道如何从 LinkedHashMap 转换为 Person,我怎么能告诉他怎么做呢?
我尝试使用的另一个序列化器是 Jackson2JsonRedisSerializer:
@Bean
@Primary
public RedisCacheConfiguration defaultCacheConfig(ObjectMapper objectMapper) {
Jackson2JsonRedisSerializer<Person> serializer = new Jackson2JsonRedisSerializer<>(Person.class);
serializer.setObjectMapper(objectMapper);
return RedisCacheConfiguration.defaultCacheConfig()
.serializeKeysWith(
SerializationPair.fromSerializer(
new StringRedisSerializer()
)
)
.serializeValuesWith(
SerializationPair.fromSerializer(
serializer
)
)
.prefixKeysWith("");
}
这样,我必须为保存在 redis 缓存中的每个对象声明一个 bean,但我可以正确序列化/反序列化。
当我直接在 redis 缓存中插入 JSON 时,我无法使用此序列化程序对其进行反序列化,序列化程序只会给我一个 Person 对象,其名称、电子邮件和 id 属性为空。有没有办法来解决这个问题?
如果有办法改善我的问题,请告诉我。
红糖糍粑
斯蒂芬大帝
眼眸繁星
相关分类