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

本文探讨了Spring-data-redis的JdkSerializationRedisSerializer和StringRedisSerializer两种序列化方案,通过源码分析和性能测试,揭示它们的工作原理和优缺点。测试结果显示,尽管两者在插入性能上的差距不大,但随着数据量增加,StringRedisSerializer占用的服务器资源更少。
最低0.47元/天 解锁文章
7722

被折叠的 条评论
为什么被折叠?



