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

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

1.添加redis、fastjson的支持

 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
 </dependency>
   <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.31</version>
    </dependency>

2.在application.properties中配置redis

spring.redis.host=localhost
spring.redis.port=6379
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1

3。在Application中

@SpringBootApplication
public class Application extends WebMvcConfigurerAdapter{
    public static void main(String[] args) {
        ParserConfig.getGlobalInstance().addAccept("com. mypackage.entity.");
        SpringApplication.run(Application.class,args);
    }

@Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);

        FastJsonHttpMessageConverter4 converter = new FastJsonHttpMessageConverter4();
        FastJsonConfig config = new FastJsonConfig();
        config.setSerializerFeatures(SerializerFeature.WriteMapNullValue,SerializerFeature.PrettyFormat,SerializerFeature.WriteNullListAsEmpty);

        converter.setFastJsonConfig(config);

        converters.add(converter);

    }
}

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

ParserConfig.getGlobalInstance().setAutoTypeSupport(true); 

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

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    @Bean
    public KeyGenerator wiselyKeyGenerator(){
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };

    }
    @Bean
    public CacheManager cacheManager(
            @SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
        return new RedisCacheManager(redisTemplate);
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate(
            RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        FastJsonRedisSerializer<Object> serializer = new FastJsonRedisSerializer<>(Object.class);
        template.setValueSerializer(serializer);
        template.afterPropertiesSet();
        return template;
    }

    private static class FastJsonRedisSerializer<T> implements RedisSerializer<T> {

        private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

        private Class<T> clazz;

        public FastJsonRedisSerializer(Class<T> clazz) {
            this.clazz = clazz;
        }

        @Override
        public byte[] serialize(T t) throws SerializationException {
            if (t == null) {
                return new byte[0];
            }
            return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
        }

        @Override
        public T deserialize(byte[] bytes) throws SerializationException {
            if (bytes == null || bytes.length <= 0) {
                return null;
            }
            String str = new String(bytes, DEFAULT_CHARSET);
            return (T) JSON.parseObject(str, clazz);
        }
    }

}

这里的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. Hibernate乐观锁和悲观锁

    Hibernate支持两种锁机制: 即通常所说的"悲观锁(Pessimistic Locking)"和 "乐观锁(OptimisticLocking)". 悲观 ...

  2. 一个想法照进现实-《IT连》创业项目:三天的风投对接活动内幕分享

    前言: 话说出来创业的,都有一颗寻找风投的心,只因都有一个共同的特征:缺钱. 有的只是缺几十万,有的缺几百万,有的缺几千万,有的缺几个亿. 中国的市场,只要有需求,就有服务,只要有服务,就多了套路. ...

  3. Linux命令语句秘籍

    系统管理命令 stat              显示指定文件的详细信息,比ls更详细 who               显示在线登陆用户 whoami          显示当前操作用户 host ...

  4. 浅谈python 手机crash和app crash循环执行问题

    ----------------引子---------------- app自动化测试人员经常遇见的问题,第一:手机抛的异常导致脚本循环停止!!!!!!!!第二:app抛的异常导致脚本循环停止!!!! ...

  5. keepalived工作原理

    keepalived是一个类似于Layer2,4,7交换机制的软件.是Linux集群管理中保证集群高可用的一个服务软件,其功能是用来防止单点故障.   keepalived的工作原理:         ...

  6. webpack学习笔记(二)-- 初学者常见问题及解决方法

    这篇文章是webpack学习第二篇,主要罗列了本人在实际操作中遇到的一些问题及其解决方法,仅供参考,欢迎提出不同意见. 注:本文假设读者已有webpack方面相关知识,故文中涉及到的专有名词不做另外解 ...

  7. 如何在RecyclerView上面实现"拖放"和"滑动删除"-2

    拖动手柄 在设计一个支持"拖放"的列表时, 通常提供一个在触摸时初始化拖拽的"拖动手柄". 因其可发现性和可用性而被Material Guidelines所推荐 ...

  8. 基于Intranet的零件库管理信息系统设计--part01

    好吧,临近毕业的我,毕业设计还没开始做呢.时间不等人,再过两个月就要答辩了,我得开始做我的毕设了,虽然我现在还没能力完全把毕设做出来,但总得先迈出第一步吧.今天先做一小部分. 话不多说,先来看我得毕业 ...

  9. 读书笔记 effective c++ Item 36 永远不要重新定义继承而来的非虚函数

    1. 为什么不要重新定义继承而来的非虚函数——实际论证 假设我告诉你一个类D public继承类B,在类B中定义了一个public成员函数mf.Mf的参数和返回类型并不重要,所以假设它们都是void. ...

  10. 搭建ntp 时钟服务器_Linux

    一.搭建时间同步服务器1.编译安装ntp serverwget [url]http://www.eecis.udel.edu/~ntp/ntp_spool/ntp4/ntp-4.2.4p4.tar.g ...