1. 程式人生 > >springboot redis配置Fastjson序列化方式

springboot redis配置Fastjson序列化方式

前言

專案中由於使用FastJson替換Jackon為預設Json序列化方式,配置redis使用Fastjson進行序列化

序列化配置

redis傳入的序列化器必須實現RedisSerializer介面:

 public void setValueSerializer(RedisSerializer<?> serializer) {
        this.valueSerializer = serializer;
    }

定義FastJson序列化器:

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;
    }

    @Override
    public byte[] serialize(T t) throws SerializationException {
        if (t == null) {
            return new byte[0];
        }
        return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
    }

    @Override
    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);
    }

}
設定RedisTemplate的序列化方式

    @Configuration
    public class RedisConfig {


        @Bean
        public RedisSerializer fastJson2JsonRedisSerializer() {
            return new FastJson2JsonRedisSerializer<Object>(Object.class);
        }

        @Bean
        public RedisTemplate initRedisTemplate(RedisConnectionFactory redisConnectionFactory, RedisSerializer fastJson2JsonRedisSerializer) throws Exception {
            RedisTemplate redisTemplate = new RedisTemplate();
            redisTemplate.setConnectionFactory(redisConnectionFactory);
            redisTemplate.setValueSerializer(fastJson2JsonRedisSerializer);
            redisTemplate.setKeySerializer(new StringRedisSerializer());
            redisTemplate.afterPropertiesSet();
            return redisTemplate;
        }
    }

完成序列化