Spring 使用 Jackson 序列化器的 Redis 缓存:如何处理多种类型的域对象

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

我的网络应用程序中有很多类型的域对象,例如MemberModelPostModelCreditsModel等。我发现在配置JacksonJsonRedisSerializer的时候需要对象的类型,所以我指定了Object.class。但是反序列化对象时出现错误。

要解决这个问题,我有两个选择:

有什么优雅的方法可以解决这个问题吗?谢谢!

有一个开放的 PR #145 available. Untill that one is merged one can pretty much just implement a RedisSerializer the way it is done in GenericJackson2JsonRedisSerializer 配置使用的 ObjectMapper 以在 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);