在 Spring MVC 中集成 Fastjson
如果你使用 Spring MVC 来构建 Web 应用并对性能有较高的要求的话,可以使用
Fastjson 提供的FastJsonHttpMessageConverter 来替换 Spring MVC 默认的 HttpMessageConverter 以提高 @RestController @ResponseBody @RequestBody 注解的 JSON序列化速度。下面是配置方式,非常简单。
XML式
如果是使用 XML 的方式配置 Spring MVC 的话,只需在 Spring MVC 的 XML 配置文件中加入下面配置即可。
<mvc:annotation-driven> <mvc:message-converters> <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"/> </mvc:message-converters> </mvc:annotation-driven>
通常默认配置已经可以满足大部分使用场景,如果你想对它进行自定义配置的话,你可以添加 FastJsonConfig Bean。
<mvc:annotation-driven> <mvc:message-converters> <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <property name="fastJsonConfig" ref="fastJsonConfig"/> </bean> </mvc:message-converters> </mvc:annotation-driven> <bean id="fastJsonConfig" class="com.alibaba.fastjson.support.config.FastJsonConfig"> <!-- 自定义配置... --> </bean>
编程式
如果是使用编程的方式(通常是基于 Spring Boot 项目)配置 Spring MVC 的话只需继承 WebMvcConfigurerAdapter 覆写 configureMessageConverters 方法即可,就像下面这样。
@Configuration public class WebMvcConfigurer extends WebMvcConfigurerAdapter { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter(); //自定义配置... //FastJsonConfig config = new FastJsonConfig(); //config.set ... //converter.setFastJsonConfig(config); converters.add(converter); } }
在 Spring Data Redis 中集成 Fastjson
编程式
如果是使用编程的方式(通常是基于 Spring Boot 项目)配置 RedisTemplate 的话只需在你的配置类(被@Configuration注解修饰的类)中显式创建 RedisTemplate Bean,设置 Serializer 即可。
@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; }
通常使用 GenericFastJsonRedisSerializer 即可满足大部分场景,如果你想定义特定类型
专用的 RedisTemplate 可以使用 FastJsonRedisSerializer 来代替
GenericFastJsonRedisSerializer ,配置是类似的。
参考
阿里FastJson的使用_json_qq_30920821的博客-CSDN博客
https://blog.csdn.net/qq_30920821/article/details/78417690