今天我们来讲讲怎么在spring boot 中整合redis 实现对数据库查询结果的缓存。
首先第一步要做的就是在pom.xml文件添加spring-boot-starter-data-redis。
要整合缓存,必不可少的就是我们要继承一个父类CachingConfigurerSupport。我们先看看这个类的源码

  1. public class CachingConfigurerSupport implements CachingConfigurer {
  2. // Spring's central cache manage SPI ,
  3. @Override
  4. @Nullable
  5. public CacheManager cacheManager() {
  6. return null;
  7. }
  8. //key的生成策略
  9. @Override
  10. @Nullable
  11. public KeyGenerator keyGenerator() {
  12. return null;
  13. }
  14. //Determine the Cache instance(s) to use for an intercepted method invocation.
  15. @Override
  16. @Nullable
  17. public CacheResolver cacheResolver() {
  18. return null;
  19. }
  20. //缓存错误处理
  21. @Override
  22. @Nullable
  23. public CacheErrorHandler errorHandler() {
  24. return null;
  25. }
  26. }

RedisConfig类

  1. @Configuration
  2. @EnableCaching
  3. public class RedisConfig extends CachingConfigurerSupport {
  4. @Bean
  5. RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) {
  6. RedisMessageListenerContainer container = new RedisMessageListenerContainer();
  7. container.setConnectionFactory(connectionFactory);
  8. container.addMessageListener(listenerAdapter, new PatternTopic("chat"));
  9. return container;
  10. }
  11. @Bean
  12. MessageListenerAdapter listenerAdapter(Receiver receiver) {
  13. return new MessageListenerAdapter(receiver, "receiveMessage");
  14. }
  15. @Bean
  16. Receiver receiver(CountDownLatch latch) {
  17. return new Receiver(latch);
  18. }
  19. @Bean
  20. CountDownLatch latch() {
  21. return new CountDownLatch(1);
  22. }
  23. public class Receiver {
  24. private CountDownLatch latch;
  25. @Autowired
  26. public Receiver(CountDownLatch latch) {
  27. this.latch = latch;
  28. }
  29. public void receiveMessage(String message) {
  30. latch.countDown();
  31. }
  32. }
  33. @Bean
  34. public KeyGenerator myKeyGenerator() {
  35. return new KeyGenerator() {
  36. @Override
  37. public Object generate(Object o, Method method, Object... objects) {
  38. StringBuilder sb = new StringBuilder();
  39. sb.append(o.getClass().getName());
  40. sb.append(method.getName());
  41. for (Object obj : objects) {
  42. sb.append(JSON.toJSONString(obj));
  43. }
  44. return sb.toString();
  45. }
  46. };
  47. }
  48. /**
  49. * @param redisConnectionFactory
  50. * @return
  51. * @// TODO: 2018/4/27 redis fastjson序列化
  52. */
  53. @Bean
  54. @ConditionalOnMissingBean(name = "redisTemplate")
  55. public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
  56. RedisTemplate<Object, Object> template = new RedisTemplate<>();
  57. //使用fastjson序列化
  58. FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
  59. // 全局开启AutoType,不建议使用
  60. // ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
  61. // 建议使用这种方式,小范围指定白名单
  62. ParserConfig.getGlobalInstance().addAccept("com.developlee.models.");
  63. // value值的序列化采用fastJsonRedisSerializer
  64. template.setValueSerializer(fastJsonRedisSerializer);
  65. template.setHashValueSerializer(fastJsonRedisSerializer);
  66. // key的序列化采用StringRedisSerializer
  67. template.setKeySerializer(new StringRedisSerializer());
  68. template.setHashKeySerializer(new StringRedisSerializer());
  69. template.setConnectionFactory(redisConnectionFactory);
  70. return template;
  71. }
  72. @Bean
  73. @ConditionalOnMissingBean(StringRedisTemplate.class)
  74. public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
  75. StringRedisTemplate template = new StringRedisTemplate();
  76. template.setConnectionFactory(redisConnectionFactory);
  77. return template;
  78. }
  79. /**
  80. * @return
  81. * @// TODO: 2018/4/27 设置redis 缓存时间 5 分钟
  82. */
  83. @Bean
  84. public RedisCacheConfiguration redisCacheConfiguration() {
  85. FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
  86. RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig();
  87. configuration = configuration.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(fastJsonRedisSerializer)).entryTtl(Duration.ofMinutes(5));
  88. return configuration;
  89. }
  90. }

这段代码中,重点关注对象是RedisTemplate 和StringRedisTemplate还有RedisMessageListenerContainer,RedisTemplate和StringRedisTemplate设置了一些序列化的参数和指定序列化的范围(主要为了防止黑客利用Redis的序列化漏洞),@ConditionalOnMissingBean注解的意思就是如果容器中没有这个类型Bean就选择当前Bean。RedisMessageListenerContainer是为Redis消息侦听器提供异步行为的容器,主要处理低层次的监听、转换和消息发送的细节。

再来看看application.xml我们的配置 , so easy~~

  1. spring:
  2. redis:
  3. database: 0 # Redis数据库索引(默认为0)
  4. host: 192.168.0.100 # Redis服务器地址 (默认为127.0.0.1)
  5. port: 6379 # Redis服务器连接端口 (默认为6379)
  6. password: 123456 # Redis服务器连接密码(默认为空)
  7. timeout: 2000 # 连接超时时间(毫秒)
  8. cache:
  9. type: redis

接下来我们就可以使用Redis缓存了,在Service层我们用注解@Cacheable来缓存查询的结果。

  1. @Cacheable(value= "orderDetailCache", keyGenerator = "myKeyGenerator", unless = "#result eq null")
  2. public OrderDetailEntity findOrderDetail(OrderDetailEntity orderDetailEntity) {
  3. return orderDetailDao.findEntity(orderDetailEntity);
  4. }

精通SpringBoot--整合Redis实现缓存的更多相关文章

  1. springBoot整合redis(作缓存)

    springBoot整合Redis 1,配置Redis配置类 package org.redislearn.configuration; import java.lang.reflect.Method ...

  2. SpringBoot整合Redis案例缓存首页数据、缓解数据库压力

    一.硬编码方式 1.场景 由于首页数据变化不是很频繁,而且首页访问量相对较大,所以我们有必要把首页数据缓存到redis中,减少数据库压力和提高访问速度. 2.RedisTemplate Jedis是R ...

  3. SpringBoot整合Redis、mybatis实战,封装RedisUtils工具类,redis缓存mybatis数据 附源码

    创建SpringBoot项目 在线创建方式 网址:https://start.spring.io/ 然后创建Controller.Mapper.Service包 SpringBoot整合Redis 引 ...

  4. SpringBoot 整合 Redis缓存

    在我们的日常项目开发过程中缓存是无处不在的,因为它可以极大的提高系统的访问速度,关于缓存的框架也种类繁多,今天主要介绍的是使用现在非常流行的NoSQL数据库(Redis)来实现我们的缓存需求. Spr ...

  5. Redis-基本概念、java操作redis、springboot整合redis,分布式缓存,分布式session管理等

    NoSQL的引言 Redis数据库相关指令 Redis持久化相关机制 SpringBoot操作Redis Redis分布式缓存实现 Resis中主从复制架构和哨兵机制 Redis集群搭建 Redis实 ...

  6. SpringBoot整合Redis、ApachSolr和SpringSession

    SpringBoot整合Redis.ApachSolr和SpringSession 一.简介 SpringBoot自从问世以来,以其方便的配置受到了广大开发者的青睐.它提供了各种starter简化很多 ...

  7. SpringBoot整合Redis及Redis工具类撰写

            SpringBoot整合Redis的博客很多,但是很多都不是我想要的结果.因为我只需要整合完成后,可以操作Redis就可以了,并不需要配合缓存相关的注解使用(如@Cacheable). ...

  8. springboot整合redis(注解形式)

    springboot整合redis(注解形式) 准备工作 springboot通常整合redis,采用的是RedisTemplate的形式,除了这种形式以外,还有另外一种形式去整合,即采用spring ...

  9. springboot整合redis——redisTemplate的使用

    一.概述 相关redis的概述,参见Nosql章节 redisTemplate的介绍,参考:http://blog.csdn.net/ruby_one/article/details/79141940 ...

  10. 九、springboot整合redis二之缓冲配置

    1.创建Cache配置类 @Configuration @EnableCaching public class RedisCacheConfig extends CachingConfigurerSu ...

随机推荐

  1. 车牌号校验js

    var regExp = /(^[\u4E00-\u9FA5]{1}[A-Z0-9]{6}$)|(^[A-Z]{2}[A-Z0-9]{2}[A-Z0-9\u4E00-\u9FA5]{1}[A-Z0-9 ...

  2. winform-Chrome-CefSharp库

    相关资源 教程地址:Winform下CefSharp的引用.配置.实例与报错排除 支持html5:http://www.html5tricks.com/demo/html5-css3-windmill ...

  3. js执行上下文和执行栈

    执行上下文就是JavaScript 在被解析和运行时环境的抽象概念,JavaScript 运行任何代码都是在执行上下文环境中运行的,执行上下文包括三个周期:创建——运行——销毁,重点说一下创建环节. ...

  4. .net笔试题一(简答题)

    1. 简述 private. protected. public. internal 修饰符的访问权限答:private : 私有成员, 在类的内部才可以访问. protected : 保护成员,该类 ...

  5. Rematch Redux的替代品

    前言:Rematch和vuex很像. 文档:https://github.com/yurizhang/rematch 简介: 先看看rematch的官方介绍: Rematch是没有boilerplat ...

  6. Canny边缘检测学习

    Canny边缘检测学习:http://www.open-open.com/lib/view/open1453460512558.html 高斯滤波学习:http://www.cnblogs.com/q ...

  7. 构建第一个Spring Boot2.0应用之项目创建(一)

     1.开发环境 IDE: JAVA环境: Tomcat: 2.使用Idea生成spring boot项目 以下是使用Idea生成基本的spring boot的步骤. (1)创建工程第一步 (2)创建工 ...

  8. https 双向验证

    服务器配置 服务器秘钥   服务器公钥证书  ,客户端公钥证书 客户端配置  客户端秘钥+密码 服务器公钥证书 目前android验证ok,pc浏览器添加客户端秘钥证书  ,访问还是失败,待继续查找资 ...

  9. uvm_tlm——TLM1事务级建模方法(一)

    TLM(事务级建模方法,Transaction-level modeling)是一种高级的数字系统模型化方法,它将模型间的通信细节与函数单元或通信架构的细节分离开来.通信机制(如总线或者FIFO)被建 ...

  10. python使用浮点类型float计算后,数值不对_20180827

    在练习时,输入如下代码: 结果不准确. 原因:https://blog.csdn.net/bitcarmanlee/article/details/51179572 浮点数一个普遍的问题就是在计算机的 ...