Spring cache with Redis using the Jackson serializer: how to deal with several types of domain objects

In my web application, there are many types of domain objects, such as MemberModel, PostModel, CreditsModel, etc. I found that the type of the object is needed when setting up JacksonJsonRedisSerializer, so I pointed out Object.class. But when deserializing the objects, I got an error.

To get around this, I have 2 options:

  • Use instead JdkSerializationRedisSerializer. But the result of serialization is too long, so it will consume a lot of memory in Redis.
  • Set up a serializer for each domian object, which means that if I have 50 domain objects, then I need to set up 50 serializers. But this is obviously quite tiring.

Is there an elegant way to solve this problem? Thank!

+4
source share
1 answer

There is available open PR # 145 . Until it is merged, you can simply implement RedisSerializerhow this is done in the GenericJackson2JsonRedisSerializer by configuring the ObjectMappertype information used for inlcude in json.

ObjectMapper mapper = new ObjectMapper();
mapper.enableDefaultTyping(DefaultTyping.NON_FINAL, As.PROPERTY);

byte[] bytes = mapper.writeValueAsBytes(domainObject);

// using Object.class allows the mapper fall back to the default typing.
// one could also use a concrete domain type if known to avoid the cast.
DomainObject target = (DomainObject) mapper.readValue(bytes, Object.class);
+5
source

All Articles