概括
一般redis的序列化方式主要有:字符串序列化、json序列化、xml序列化、jdk序列化,具体可查阅org.springframework.data.redis.serializer.RedisSerializer 的实现类,其中对于json序列化,官方实现的是jackson的序列化,此外fastjson也有对应的实现。
源码分析
下面开始对spring-data-redis的源码稍加分析。
key、hash key的序列化一般使用如下方式:
...
/**
* Simple String to byte[] (and back) serializer. Converts Strings into bytes and vice-versa using the specified charset
* (by default UTF-8).
* <p>
* Useful when the interaction with the Redis happens mainly through Strings.
* <p>
* Does not perform any null conversion since empty strings are valid keys/values.
*
* @author Costin Leau
* @author Christoph Strobl
*/
public class StringRedisSerializer implements RedisSerializer<String> {
private final Charset charset;
public StringRedisSerializer() {
this(Charset.forName("UTF8"));
}
public StringRedisSerializer(Charset charset) {
Assert.notNull(charset, "Charset must not be null!");
this.charset = charset;
}
public String deserialize(byte[] bytes) {
return (bytes == null ? null : new String(bytes, charset));
}
public byte[] serialize(String string) {
return (string == null ? null : string.getBytes(charset));
}
}
可以看出使用的是字符串的序列化很常规
value、hash value的序列化一般使用如下方式:
part I
...
/**
* Java Serialization Redis serializer. Delegates to the default (Java based) {@link DefaultSerializer serializer} and
* {@link DefaultDeserializer}. This {@link RedisSerializer serializer} can be constructed with either custom
* {@link ClassLoader} or own {@link Converter converters}.
*/
public class JdkSerializationRedisSerializer implements RedisSerializer<Object> {
// 三个构造函数
// 默认构造函数
public JdkSerializationRedisSerializer(){
this(new SerializingConverter(), new DeserializingConverter());}
// 指定ClassLoader的构造函数(热部署时可能需要用到,避免不同的类加载器搞混)
public JdkSerializationRedisSerialize