Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring cache with Redis using Jackson serializer: How to deal with multiple type of domain object

There are many types of domain objects in my web application, such as MemberModel, PostModel, CreditsModel and so on. I find that the type of the object is needed when configuring JacksonJsonRedisSerializer, so I specified Object.class. But I got error when deserializing objects.

To work around this, I've got 2 options:

  • Use JdkSerializationRedisSerializer instead. But the result of the serialization is too long so it will consume lots of memory in Redis.
  • Configure serializer for every domian objects, which means if I have 50 domain objects then I have to configure 50 serializers. But this is obviously pretty tedious.

Is there a graceful way to solve this problem? Thanks!

like image 556
Neo Avatar asked Jul 07 '15 14:07

Neo


1 Answers

There's an open PR #145 available. Untill that one is merged one can pretty much just implement a RedisSerializer the way it is done in GenericJackson2JsonRedisSerializer configuring the used ObjectMapper to inlcude type information within the 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);
like image 166
Christoph Strobl Avatar answered Sep 29 '22 16:09

Christoph Strobl