springboot-redis使用fastjson2
1、pom
注:springboot2.*使用fastjson2-extension-spring5,3.*使用fastjson2-extension-spring6
<fastjson.version>2.0.37</fastjson.version>
<!-- json -->
<dependency><groupId>com.alibaba.fastjson2</groupId><artifactId>fastjson2</artifactId><version>${fastjson.version}</version>
</dependency>
<dependency><groupId>com.alibaba.fastjson2</groupId><artifactId>fastjson2-extension</artifactId><version>${fastjson.version}</version>
</dependency>
<dependency><groupId>com.alibaba.fastjson2</groupId><artifactId>fastjson2-extension-spring5</artifactId><version>${fastjson.version}</version>
</dependency>
2、RedisConfig
import com.alibaba.fastjson2.support.spring.data.redis.FastJsonRedisSerializer;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;@Log4j2
@Configuration
public class RedisConfig {@Autowiredprivate RedisConnectionFactory factory;@Bean(name = "redisTemplate")public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {RedisTemplate<Object, Object> template = new RedisTemplate<>();template.setConnectionFactory(redisConnectionFactory);//序列化//如需使用类自动化装配(redis直接存储类对象),请使用类FastJson2RedisSerializer序列化FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);// value值的序列化采用fastJsonRedisSerializertemplate.setDefaultSerializer(fastJsonRedisSerializer);log.info("redis client初始化完成");return template;}
}
3、FastJson2RedisSerializer
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.filter.Filter;
import org.springframework.data.redis.serializer.RedisSerializer;public class FastJson2RedisSerializer<T> implements RedisSerializer<T> {static final Filter autoTypeFilter = JSONReader.autoTypeFilter(// 按需加上需要支持自动类型的类名前缀,范围越小越安全"com.***.***.***","com.***.***.***");private Class<T> clazz;public FastJson2RedisSerializer(Class<T> clazz) {super();this.clazz = clazz;}@Overridepublic byte[] serialize(T t) {if (t == null) {return new byte[0];}return JSON.toJSONBytes(t, JSONWriter.Feature.WriteClassName);}@Overridepublic T deserialize(byte[] bytes) {if (bytes == null || bytes.length <= 0) {return null;}return JSON.parseObject(bytes, clazz, autoTypeFilter);}
}