Spring 使用 Jackson 序列化器的 Redis 缓存:如何处理多种类型的域对象
Spring cache with Redis using Jackson serializer: How to deal with multiple type of domain object
我的网络应用程序中有很多类型的域对象,例如MemberModel
、PostModel
、CreditsModel
等。我发现在配置JacksonJsonRedisSerializer
的时候需要对象的类型,所以我指定了Object.class
。但是反序列化对象时出现错误。
要解决这个问题,我有两个选择:
- 改用
JdkSerializationRedisSerializer
。但是序列化的结果太长,会占用Redis大量内存。
- 为每个域对象配置序列化器,这意味着如果我有 50 个域对象,那么我必须配置 50 个序列化器。但这显然很乏味。
有什么优雅的方法可以解决这个问题吗?谢谢!
有一个开放的 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);
我的网络应用程序中有很多类型的域对象,例如MemberModel
、PostModel
、CreditsModel
等。我发现在配置JacksonJsonRedisSerializer
的时候需要对象的类型,所以我指定了Object.class
。但是反序列化对象时出现错误。
要解决这个问题,我有两个选择:
- 改用
JdkSerializationRedisSerializer
。但是序列化的结果太长,会占用Redis大量内存。 - 为每个域对象配置序列化器,这意味着如果我有 50 个域对象,那么我必须配置 50 个序列化器。但这显然很乏味。
有什么优雅的方法可以解决这个问题吗?谢谢!
有一个开放的 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);