当前位置: 首页 > 工具软件 > fastJSON 2 > 使用案例 >

Redis使用FastJson序列化/FastJson2JsonRedisSerializer

松景铄
2023-12-01

背景

最近在用SpringBoot+Redis+SpringCache做个缓存。但是发现网上很多默认都是用的jackson序列化,那是多么古老,fastjson才是王道,所以这才有了这个FastJson2JsonRedisSerializer。

FastJson2JsonRedisSerializer.java

网上的fastjson似乎都一般般,这个是网上的一个加强版

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import com.alibaba.fastjson.parser.ParserConfig;
import org.springframework.util.Assert;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
/**
 * FastJson2JsonRedisSerializer
 *  Redis使用FastJson序列化
 *  by zhengkai.blog.csdn.net
 */
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> {
    private ObjectMapper objectMapper = new ObjectMapper();
    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    private Class<T> clazz;
    
   static {
   		ParserConfig.getGlobalInstance().setAutoTypeSupport(true); 
   		//如果遇到反序列化autoType is not support错误,请添加并修改一下包名到bean文件路径
       // ParserConfig.getGlobalInstance().addAccept("com.xxxxx.xxx");
    }
    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 JSON.parseObject(str, clazz);
    }
    public void setObjectMapper(ObjectMapper objectMapper) {
        Assert.notNull(objectMapper, "'objectMapper' must not be null");
        this.objectMapper = objectMapper;
    }

    protected JavaType getJavaType(Class<?> clazz) {
        return TypeFactory.defaultInstance().constructType(clazz);
    }

}

RedisConfig

用fastjson来序列化value的值,用string来序列化key的值。


@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
        //Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
        //使用Fastjson2JsonRedisSerializer来序列化和反序列化redis的value值 by zhengkai
        FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);

        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(mapper);

        template.setValueSerializer(serializer);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }

"autoType is not support"问题

用tomcat+nginx+redis在负载均衡情况下做使用fastjson反序列化可能会遇到

com.alibaba.fastjson.JSONException: autoType is not support

原因是是fastjson默认是开启的了autoType,只需要在FastJson2JsonRedisSerializer里面设置一个静态变量添加bean/domain/entity的对应包名进行白名单排除即可。感谢@Alan老三 的反馈。

    static {
        ParserConfig.getGlobalInstance().addAccept("com.xxx.xxx.entity");
    }

或者使用setAutoTypeSupport=true的全局设置

static {
	ParserConfig.getGlobalInstance().setAutoTypeSupport(true); 
}
 类似资料: