使用spring-data-redis的时候,其序列化工具自带:
这些类,进行序列化,主要使用的是Jackson2JsonRedisSerializer,编码如下:
@Bean @SuppressWarnings({ "rawtypes", "unchecked" }) public Jackson2JsonRedisSerializer jackson2JsonRedisSerializer() { Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); return jackson2JsonRedisSerializer; } @Bean @SuppressWarnings("rawtypes") public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory, RedisSerializer fastJson2JsonRedisSerializer) { StringRedisTemplate template = new StringRedisTemplate(factory); template.setValueSerializer(fastJson2JsonRedisSerializer); template.afterPropertiesSet(); return template; }
但是使用jackson会有一个问题,因为我springMVC同样是使用的jackson,这样的话由于一些发送给前端的json是需要一定的处理的,如jsonIgnore之类的,这样会在进行缓存时同样处理掉,达不到缓存的目的,于是决定在spring-data-redis进行缓存时,将jackson的序列化由fastjson替换掉。
首先需要一个RedisSerializer:
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> { public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); private Class<T> clazz; public FastJson2JsonRedisSerializer(Class<T> clazz) { super(); this.clazz = clazz; } public byte[] serialize(T t) throws SerializationException { if (t == null) { return new byte[0]; } return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET); } public T deserialize(byte[] bytes) throws SerializationException { if (bytes == null || bytes.length <= 0) { return null; } String str = new String(bytes, DEFAULT_CHARSET); return (T) JSON.parseObject(str, clazz); } }
此类需要实现RedisSerializer接口。
然后set到RedisTemplate上:
@Bean @SuppressWarnings("rawtypes") public RedisSerializer fastJson2JsonRedisSerializer() { return new FastJson2JsonRedisSerializer<Object>(Object.class); } @Bean @SuppressWarnings("rawtypes") public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory, RedisSerializer fastJson2JsonRedisSerializer) { StringRedisTemplate template = new StringRedisTemplate(factory); template.setValueSerializer(fastJson2JsonRedisSerializer); template.afterPropertiesSet(); return template; }
结束