小编kri*_*onz的帖子

为 spring-boot redis 缓存配置配置一个新的序列化程序

我一直在尝试更改 spring-boot redis 缓存的默认序列化程序,因为我想从默认更改为 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("");
}
Run Code Online (Sandbox Code Playgroud)

当我使用这个序列化程序时,序列化工作正常,所有内容都存储在 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
Run Code Online (Sandbox Code Playgroud)

缓存的使用方式如下:

@Cacheable(cacheNames = "person", key = "'person:'.concat(#post.id)")
public Person findPostAuthor(Post post){
}
Run Code Online (Sandbox Code Playgroud)

序列化器不知道如何从 LinkedHashMap 转换为 Person,我怎么能告诉他怎么做呢?

我尝试使用的另一个序列化程序是 Jackson2JsonRedisSerializer:

@Bean
@Primary
public RedisCacheConfiguration defaultCacheConfig(ObjectMapper objectMapper) { …
Run Code Online (Sandbox Code Playgroud)

java caching redis spring-data-redis spring-boot

2
推荐指数
1
解决办法
7775
查看次数

标签 统计

caching ×1

java ×1

redis ×1

spring-boot ×1

spring-data-redis ×1