Quantcast
Channel: Active questions tagged redis+java - Stack Overflow
Viewing all articles
Browse latest Browse all 2203

Configure a new serializer for spring-boot redis cache config

$
0
0

I have been trying to change the default serializer for the spring-boot redis cache because i want to change from the Default to one of the Jackson2Json implementations. There are two implementations from the Jackson2Json library one of them is the: GenericJackson2JsonRedisSerializer, which i can use on the following bean instantiation:

@Bean@Primarypublic RedisCacheConfiguration defaultCacheConfig(ObjectMapper objectMapper) {    return RedisCacheConfiguration.defaultCacheConfig()        .serializeKeysWith(            SerializationPair.fromSerializer(                new StringRedisSerializer()            )        )        .serializeValuesWith(            SerializationPair.fromSerializer(                new GenericJackson2JsonRedisSerializer(objectMapper)            )        )        .prefixKeysWith("");}

When i use this serializer the serialization works fine, everything is stored on the redis server, but when o try to deserialize the JSON stored on the redis server i receive the following exception:

java.util.LinkedHashMap cannot be cast to tutorial.Person with root causejava.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to tutorial.Person

The cache is being used on the following way:

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

The serializer doesn't know how to convert from the LinkedHashMap to the Person, how can i tell him how to do it?

The other serializer i tried to work with was the Jackson2JsonRedisSerializer:

@Bean@Primarypublic 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("");}

On this way i would have to declare a bean for each object saved on the redis cache, but i can serialize / deserialize correctly.

When i insert a JSON directly on the redis cache, i can't deserialize it with this serializer the serializer just gives me a Person object with empty name, email, and id properties. Is there a way to fix this?

If there is a way to improve my question, please let me know.


Viewing all articles
Browse latest Browse all 2203

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>