vRedisCacheManager构造函数
按 Ctrl+C 复制代码
/**
* Construct a {@link RedisCacheManager}.
*
* @param redisOperations
*/
@SuppressWarnings("rawtypes")
public RedisCacheManager(RedisOperations redisOperations) {
this(redisOperations, Collections. emptyList());
}
/**
* Construct a static {@link RedisCacheManager}, managing caches for the specified cache names only.
*
* @param redisOperations
* @param cacheNames
* @since 1.2
*/
@SuppressWarnings("rawtypes")
public RedisCacheManager(RedisOperations redisOperations, Collection cacheNames) {
this.redisOperations = redisOperations;
setCacheNames(cacheNames);
}
按 Ctrl+C 复制代码
RedisCacheManager需要一个 RedisOperations实例,一般是RedisTemplate。还有一个不必须的缓存名称集合参数。
复制代码
protected RedisCache createCache(String cacheName) {
long expiration = computeExpiration(cacheName);
return new RedisCache(cacheName, (usePrefix ? cachePrefix.prefix(cacheName) : null), redisOperations, expiration);
}
复制代码
在创建缓存时,通过RedisCache的构造函数传入 redisOperations(即RedisTemplate实例)。
v设置全局通用的序列化器
v GenericJackson2JsonRedisSerializer
复制代码
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
GenericJackson2JsonRedisSerializer serializer = new GenericJackson2JsonRedisSerializer();
User user = new User();
user.setName("hjzgg");
user.setAge(26);
System.out.println(serializer.deserialize(serializer.serialize(user)));
public static class User {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("name", name)
.add("age", age)
.toString();
}
}
复制代码
调试发现,序列化内容加入了对象的类型信息,如下。
查看GenericJackson2JsonRedisSerializer构造函数,序列化和反序列化的实现是通过Jackson的ObjectMapper完成的。并开启了默认类型的配置。
复制代码
/**
* 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);
}
}
复制代码
v Protostuff序列化和反序列化
复制代码
import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import org.springframework.data.redis.serializer.RedisSerializer;
public class ProtostuffRedisSerializer implements RedisSerializer