fastjson2配置springboot转换器

前言

最近项目上升级了fastjson2,据说2比1又快了,重点是之前的fastjson漏洞太多,所以干脆直接升2了,下面记录下springboot集成消息抓换器的用法

使用

在Fastjson2中,同样可以使用FastJsonHttpMessageConverterFastJsonJsonView 为 Spring MVC 构建的 Web 应用提供更好的性能体验。

使用 FastJsonHttpMessageConverter 来替换 Spring MVC 默认的 HttpMessageConverter 以提高 @RestController @ResponseBody @RequestBody 注解的 JSON序列化和反序列化速度。

Package: com.alibaba.fastjson2.support.spring.http.converter.FastJsonHttpMessageConverter

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Configuration
@EnableWebMvc
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
//自定义配置...
FastJsonConfig config = new FastJsonConfig();
config.setDateFormat("yyyy-MM-dd HH:mm:ss");
config.setReaderFeatures(JSONReader.Feature.FieldBased, JSONReader.Feature.SupportArrayToBean);
config.setWriterFeatures(JSONWriter.Feature.WriteMapNullValue, JSONWriter.Feature.PrettyFormat);
converter.setFastJsonConfig(config);
converter.setDefaultCharset(StandardCharsets.UTF_8);
converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));
converters.add(0, converter);
}
}
在 Spring Data Redis 中集成 Fastjson2

在Fastjson2中,同样可以使用 GenericFastJsonRedisSerializerFastJsonRedisSerializer 为 Spring Data Redis 提供更好的性能体验。

使用 GenericFastJsonRedisSerializer 作为 RedisTemplateRedisSerializer 来提升JSON序列化和反序列化速度。

Package: com.alibaba.fastjson2.support.spring.data.redis.GenericFastJsonRedisSerializer

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Configuration
public class RedisConfiguration {

@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(redisConnectionFactory);

GenericFastJsonRedisSerializer fastJsonRedisSerializer = new GenericFastJsonRedisSerializer();
redisTemplate.setDefaultSerializer(fastJsonRedisSerializer);//设置默认的Serialize,包含 keySerializer & valueSerializer

//redisTemplate.setKeySerializer(fastJsonRedisSerializer);//单独设置keySerializer
//redisTemplate.setValueSerializer(fastJsonRedisSerializer);//单独设置valueSerializer
return redisTemplate;
}
}