因为项目需求,需要在spring boot环境中使用redis作数据缓存。之前的解决方案是参考的http://wiselyman.iteye.com/blog/2184884,具体使用的是Jackson2JsonRedisSerializer。但是使用后发现性能并不理想,一个简单的json请求就需要几百毫秒。

后来项目的json统一换成了fastjson,使用了FastJsonRedisSerializer后,性能大幅提升,一个请求通常只要10几毫秒。

1.添加redis、fastjson的支持

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-redis</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>com.alibaba</groupId>
  7. <artifactId>fastjson</artifactId>
  8. <version>1.2.31</version>
  9. </dependency>

2.在application.properties中配置redis

  1. spring.redis.host=localhost
  2. spring.redis.port=6379
  3. spring.redis.pool.max-idle=8
  4. spring.redis.pool.min-idle=0
  5. spring.redis.pool.max-active=8
  6. spring.redis.pool.max-wait=-1

3。在Application中

  1. @SpringBootApplication
  2. public class Application extends WebMvcConfigurerAdapter{
  3. public static void main(String[] args) {
  4. ParserConfig.getGlobalInstance().addAccept("com. mypackage.entity.");
  5. SpringApplication.run(Application.class,args);
  6. }
  7.  
  8. @Override
  9. public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
  10. super.configureMessageConverters(converters);
  11.  
  12. FastJsonHttpMessageConverter4 converter = new FastJsonHttpMessageConverter4();
  13. FastJsonConfig config = new FastJsonConfig();
  14. config.setSerializerFeatures(SerializerFeature.WriteMapNullValue,SerializerFeature.PrettyFormat,SerializerFeature.WriteNullListAsEmpty);
  15.  
  16. converter.setFastJsonConfig(config);
  17.  
  18. converters.add(converter);
  19.  
  20. }
  21. }

 这里的ParserConfig.getGlobalInstance().addAccept是因为在fastjson 1.2.25之后的版本,autotype功能是受限的,需要添加白名单。具体参考https://github.com/alibaba/fastjson/wiki/enable_autotype。或者使用

  1. ParserConfig.getGlobalInstance().setAutoTypeSupport(true);

4。配置RedisConfig,具体代码如下:

  1. @Configuration
  2. @EnableCaching
  3. public class RedisConfig extends CachingConfigurerSupport {
  4. @Bean
  5. public KeyGenerator wiselyKeyGenerator(){
  6. return new KeyGenerator() {
  7. @Override
  8. public Object generate(Object target, Method method, Object... params) {
  9. StringBuilder sb = new StringBuilder();
  10. sb.append(target.getClass().getName());
  11. sb.append(method.getName());
  12. for (Object obj : params) {
  13. sb.append(obj.toString());
  14. }
  15. return sb.toString();
  16. }
  17. };
  18.  
  19. }
  20. @Bean
  21. public CacheManager cacheManager(
  22. @SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
  23. return new RedisCacheManager(redisTemplate);
  24. }
  25.  
  26. @Bean
  27. public RedisTemplate<String, String> redisTemplate(
  28. RedisConnectionFactory factory) {
  29. StringRedisTemplate template = new StringRedisTemplate(factory);
  30. FastJsonRedisSerializer<Object> serializer = new FastJsonRedisSerializer<>(Object.class);
  31. template.setValueSerializer(serializer);
  32. template.afterPropertiesSet();
  33. return template;
  34. }
  35.  
  36. private static class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
  37.  
  38. private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
  39.  
  40. private Class<T> clazz;
  41.  
  42. public FastJsonRedisSerializer(Class<T> clazz) {
  43. this.clazz = clazz;
  44. }
  45.  
  46. @Override
  47. public byte[] serialize(T t) throws SerializationException {
  48. if (t == null) {
  49. return new byte[0];
  50. }
  51. return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
  52. }
  53.  
  54. @Override
  55. public T deserialize(byte[] bytes) throws SerializationException {
  56. if (bytes == null || bytes.length <= 0) {
  57. return null;
  58. }
  59. String str = new String(bytes, DEFAULT_CHARSET);
  60. return (T) JSON.parseObject(str, clazz);
  61. }
  62. }
  63.  
  64. }

这里的SerializerFeature.WriteClassName是必须的



在spring boot环境中使用fastjson + redis的高速缓存技术的更多相关文章

  1. 【redis】5.spring boot项目中,直接在spring data jpa的Repository层使用redis +redis注解@Cacheable直接在Repository层使用,报错问题处理Null key returned for cache operation

    spring boot整合redis:http://www.cnblogs.com/sxdcgaq8080/p/8028970.html 首先,明确一下问题的场景 之前在spring boot整合re ...

  2. Spring Boot (五): Redis缓存使用姿势盘点

    1. Redis 简介 Redis 是目前业界使用最广泛的内存数据存储.相比 Memcached,Redis 支持更丰富的数据结构,例如 hashes, lists, sets 等,同时支持数据持久化 ...

  3. Spring Boot项目中使用Mockito

    本文首发于个人网站:Spring Boot项目中使用Mockito Spring Boot可以和大部分流行的测试框架协同工作:通过Spring JUnit创建单元测试:生成测试数据初始化数据库用于测试 ...

  4. 在Spring Boot项目中使用Spock测试框架

    本文首发于个人网站:在Spring Boot项目中使用Spock测试框架 Spock框架是基于Groovy语言的测试框架,Groovy与Java具备良好的互操作性,因此可以在Spring Boot项目 ...

  5. Spring Boot 2.x 缓存应用 Redis注解与非注解方式入门教程

    Redis 在 Spring Boot 2.x 中相比 1.5.x 版本,有一些改变.redis 默认链接池,1.5.x 使用了 jedis,而2.x 使用了 lettuce Redis 接入 Spr ...

  6. spring boot 环境配置(profile)切换

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  7. Spring Boot 环境变量读取 和 属性对象的绑定

    网上看到的一些方法,结合我看到的 和我们现在使用的.整理成此文: 第一种方法 参见catoop的博客之 Spring Boot 环境变量读取 和 属性对象的绑定(尊重原创) 第二种方法 class不用 ...

  8. 你真的理解 Spring Boot 项目中的 parent 吗?

    前面和大伙聊了 Spring Boot 项目的三种创建方式,这三种创建方式,无论是哪一种,创建成功后,pom.xml 坐标文件中都有如下一段引用: <parent> <groupId ...

  9. 【Spring学习】在Spring+Maven环境中使用Junit Test

    在Spring+Maven环境中使用Junit Test 前言 以前我是很讨厌写测试代码的,总觉得测试用例是测试人员写的,现在想想自己真是Too yuong too simple,接触开发多了之后发现 ...

随机推荐

  1. 本地化 NSLocal

    本地化封装了关于语言,文化以及技术约定和规范的信息.用于提供于用户所处地域相关的定制化信息和首选项信息的设置.通过获取用户的本地化信息设置,我们可以为用户提供更加友好人性化的界面设置,包括更改更改应用 ...

  2. ios录音Demo

    <AudioToolbox/AudioToolbox.h> :这个库是C的接口,偏向于底层,主要用于在线流媒体的播放 <AVFoundation/AVFoundation.h> ...

  3. 字符编码的种类:ASCII、GB2312、GBK、GB18030、Unicode、UTF-8、UTF-16、Base64

    ASCII码ASCII:https://zh.wikipedia.org/wiki/ASCIIASCII(American Standard Code for Information Intercha ...

  4. iOS切圆角的几个方法

    这几天在研究到切圆角的方法,也找了下网上的资料 ---------- 切圆角尽量避免离屏渲染. 1.直接用视图中layer中的两个属性来设置圆角,这种方法比较简单,但是及其影响性能不推荐:  @pro ...

  5. Yii2 Pjax 与 ActionForm ,不刷新提交数据

    <?php yii\widgets\Pjax::begin(['id'=>'phoneDetail']);?> <?php $form = ActiveForm::begin( ...

  6. mybatis基础学习3---特殊sql语句(备忘)

    1: 2: 3:resultMap的用法

  7. ListView的简单使用

    首先在主界面建立一个ListView的布局

  8. js全选与反选

    HTML结构: <!doctype html><html><head><meta charset="utf-8"><title ...

  9. linuxCentOs6前期简单且必要的设置

    1.修改主机名 Sudo vi /etc/sysconfig/network(需要重启) Hostname master (不需要重启,设置当前主机名为master) Hostname查看当前主机名 ...

  10. 搭建ubuntu版hadoop集群

    用到的工具:VMware.hadoop-2.7.2.tar.jdk-8u65-linux-x64.tar.ubuntu-16.04-desktop-amd64.iso 1.  在VMware上安装ub ...