SpringBoot+Redis缓存新老版本FastJson序列化使用方法(redis配置无效问题)

FastJson序列化器 实现RedisSerializer


/**
 * @Author:humorchen
 * @Date 2020/11/8 13:32
 */
@Component
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> {

    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
    static {
        
		//由于fastjson有autotype检查,将自己的包前缀加进去防止反序列化失败
        ParserConfig.getGlobalInstance().addAccept("com.humorchen");
    }

    private Class<T> clazz;
    public FastJson2JsonRedisSerializer() {
        this((Class<T>) Object.class);
    }
    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);
    }

}

老版配置方法,配置redisTemplate

@Configuration
public class RedisConfig {
    @Autowired
    private FastJson2JsonRedisSerializer fastJson2JsonRedisSerializer;
   
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(
            RedisConnectionFactory factory)
            throws UnknownHostException {
        RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
        template.setConnectionFactory(factory);
        //redis开启事务
        template.setEnableTransactionSupport(true);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(fastJson2JsonRedisSerializer);
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(fastJson2JsonRedisSerializer);
        template.setDefaultSerializer(new StringRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }
    
}

新版配置方法 配置cacheManager

@Configuration
public class RedisConfig {
    @Autowired
    private FastJson2JsonRedisSerializer fastJson2JsonRedisSerializer;
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();

        // 配置序列化
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(fastJson2JsonRedisSerializer));
        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }


}

你可能感兴趣的:(Java,数据库,redis,fastjson,springboot,序列化)