JdkSerializationRedisSerializer
和GenericFastJsonRedisSerializer
源码对比
性能对比——插入
优缺点总结
笔者在上篇中使用了阿里巴巴的fastjson
的 GenericFastJsonRedisSerializer
序列化方案貌似解决了乱码问题,但笔者之后再次排查,发现乱码问题和序列化方案并没有直接关系。想要知道答案,那么请读完此篇文章。
RedisSerializer
提供了九种序列化方案,分别为:
Spring-data-redis | fastjson |
---|---|
ByteArrayRedisSerializer | FastJsonRedisSerializer |
GenericJackson2JsonRedisSerializer | GenericFastJsonRedisSerializer |
GenericToStringSerializer | |
Jackson2JsonRedisSerializer | |
JdkSerializationRedisSerializer | |
OxmSerializer | |
StringRedisSerializer |
Redis
在储存数据时需要将数据转化为byte
数组进行存储,这一点需要提前说明,接下来这一篇文章只谈 JdkSerializationRedisSerializer
和 GenericFastJsonRedisSerializer
这两种序列化方案的相关问题。
源码对比
JdkSerializationRedisSerializer
作为默认的序列化方案,JdkSerializationRedisSerializer
有两个属性:
private final Converter<Object, byte[]> serializer;
private final Converter<byte[], Object> deserializer;
想来读者已经猜到了它大致的作用,点进Converter
中去看注释的解释:
import org.springframework.lang.Nullable;
/**
* A converter converts a source object of type {@code S} to a target of type {@code T}.
*
* <p>Implementations of this interface are thread-safe and can be shared.
*
* <p>Implementations may additionally implement {@link ConditionalConverter}.
*
* @author Keith Donald
* @since 3.0
* @param <S> the source type
* @param <T> the target type
*/
@FunctionalInterface
public interface Converter<S, T> {
/**
* Convert the source object of type {@code S} to target type {@code T}.
* @param source the source object to convert, which must be an instance of {@code S} (never {@code null})
* @return the converted object, which must be an instance of {@code T} (potentially {@code null})
* @throws IllegalArgumentException if the source cannot be converted to the desired target type
*/
@Nullable
T convert(S source);
}
大致意思就是将S型的源数据转化为T型的数据。所以现在就好理解了,JdkSerializationRedisSerializer
中的两个属性:serializer
的作用为将Object
转化为byte
数组,而deserializer
则相反,将byte
数组转化为Object
。
最重要的就是序列化和反序列化的实现了,且看源码:
public Object deserialize(@Nullable byte[] bytes) {
if (SerializationUtils.isEmpty(bytes)) {
return null;
} else {
try {
return this.deserializer