Christoph Strobl
*
@since 1.6
*/
public
class GenericJackson2JsonRedisSerializer implements RedisSerializer<Object> {
private final ObjectMapper mapper;
/**
* Creates {@link GenericJackson2JsonRedisSerializer} and configures {@link ObjectMapper} for default typing.
*/
public GenericJackson2JsonRedisSerializer() {
this((String)
null);
}
/**
* Creates {@link GenericJackson2JsonRedisSerializer} and configures {@link ObjectMapper} for default typing using the
* given {@literal name}. In case of an {@literal empty} or {@literal null} String the default
* {@link JsonTypeInfo.Id#CLASS} will be used.
*
* @param classPropertyTypeName Name of the JSON property holding type information. Can be {@literal null}.
*/
public GenericJackson2JsonRedisSerializer(String classPropertyTypeName) {
this(
new ObjectMapper());
if (StringUtils.hasText(classPropertyTypeName)) {
mapper.enableDefaultTypingAsProperty(DefaultTyping.NON_FINAL, classPropertyTypeName);
}
else {
mapper.enableDefaultTyping(DefaultTyping.NON_FINAL, As.PROPERTY);
}
}
/**
* Setting a custom-configured {@link ObjectMapper} is one way to take further control of the JSON serialization
* process. For example, an extended {@link SerializerFactory} can be configured that provides custom serializers for
* specific types.
*
* @param mapper must not be {@literal null}.
*/
public GenericJackson2JsonRedisSerializer(ObjectMapper mapper) {
Assert.notNull(mapper,
"ObjectMapper must not be null!");
this.mapper = mapper;
}
@Override
public byte[] serialize(Object source)
throws SerializationException {
if (source ==
null) {
return SerializationUtils.EMPTY_ARRAY;
}
try {
return mapper.writeValueAsBytes(source);
}
catch (JsonProcessingException e) {
throw new SerializationException(
"Could not write JSON: " + e.getMessage(), e);
}
}
@Override
public Object deserialize(byte[] source)
throws SerializationException {
return deserialize(source, Object.
class);
}
/**
* @param source can be {@literal null}.
* @param type must not be {@literal null}.
* @return {@literal null} for empty source.
* @throws SerializationException
*/
public <T> T deserialize(byte[] source, Class<T>
type)
throws SerializationException {
Assert.notNull(
type,
"Deserialization type must not be null! Pleaes provide Object.class to make use of Jackson2 default typing.");
if (SerializationUtils.isEmpty(source)) {
return null;
}
try {
return mapper.readValue(source,
type);
}
catch (Exception ex) {
throw new SerializationException(
"Could not read JSON: " + ex.getMessage(), ex);
}
}
}
然后在配置文件中使用这个GenericJackson2JsonRedisSerializer
:
<bean id="jacksonSerializer" class="com.fh.taolijie.component.GenericJackson2JsonRedisSerializer">
</bean>
重新构建部署,我们发现这个serializer可以同时支持多种不同类型的domain对象,问题解决。
版权声明:本文为博主原创文章,未经博主允许不得转载。
使用Spring Cache + Redis + Jackson Serializer缓存数据库查询结果中序列化问题的解决
标签: