【问题标题】:Spring cache with Redis using Jackson serializer: How to deal with multiple type of domain objectSpring cache with Redis using Jackson serializer:如何处理多种类型的域对象
【发布时间】:2015-09-25 03:09:02
【问题描述】:
我的web应用中有很多类型的域对象,比如MemberModel、PostModel、CreditsModel等等。我发现在配置JacksonJsonRedisSerializer的时候需要对象的类型,所以我指定了Object.class。但是反序列化对象时出现错误。
要解决这个问题,我有两个选择:
- 请改用
JdkSerializationRedisSerializer。但是序列化的结果太长了,会占用 Redis 的大量内存。
- 为每个域对象配置序列化程序,这意味着如果我有 50 个域对象,那么我必须配置 50 个序列化程序。但这显然很乏味。
有没有优雅的方法来解决这个问题?谢谢!
【问题讨论】:
标签:
spring-cache
spring-data-redis
【解决方案1】:
有一个公开的 PR #145 可用。在合并之前,几乎可以像在GenericJackson2JsonRedisSerializer 中那样实现RedisSerializer,将使用的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);