1、pom
注:springboot2.*使用fastjson2-extension-spring5,3.*使用fastjson2-extension-spring6文章来源地址https://www.toymoban.com/news/detail-610903.html
<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 {
@Autowired
private 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值的序列化采用fastJsonRedisSerializer
template.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;
}
@Override
public byte[] serialize(T t) {
if (t == null) {
return new byte[0];
}
return JSON.toJSONBytes(t, JSONWriter.Feature.WriteClassName);
}
@Override
public T deserialize(byte[] bytes) {
if (bytes == null || bytes.length <= 0) {
return null;
}
return JSON.parseObject(bytes, clazz, autoTypeFilter);
}
}
文章来源:https://www.toymoban.com/news/detail-610903.html
到了这里,关于springboot-redis使用fastjson2的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!