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

public class CachingConfigurerSupport implements CachingConfigurer {
// Spring's central cache manage SPI ,
@Override
@Nullable
public CacheManager cacheManager() {
return null;
}
//key的生成策略
@Override
@Nullable
public KeyGenerator keyGenerator() {
return null;
}
//Determine the Cache instance(s) to use for an intercepted method invocation.
@Override
@Nullable
public CacheResolver cacheResolver() {
return null;
}
//缓存错误处理
@Override
@Nullable
public CacheErrorHandler errorHandler() {
return null;
} }

RedisConfig类

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport { @Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(listenerAdapter, new PatternTopic("chat"));
return container;
} @Bean
MessageListenerAdapter listenerAdapter(Receiver receiver) {
return new MessageListenerAdapter(receiver, "receiveMessage");
} @Bean
Receiver receiver(CountDownLatch latch) {
return new Receiver(latch);
} @Bean
CountDownLatch latch() {
return new CountDownLatch(1);
} public class Receiver {
private CountDownLatch latch; @Autowired
public Receiver(CountDownLatch latch) {
this.latch = latch;
} public void receiveMessage(String message) {
latch.countDown();
}
} @Bean
public KeyGenerator myKeyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object o, Method method, Object... objects) {
StringBuilder sb = new StringBuilder();
sb.append(o.getClass().getName());
sb.append(method.getName());
for (Object obj : objects) {
sb.append(JSON.toJSONString(obj));
}
return sb.toString();
}
};
} /**
* @param redisConnectionFactory
* @return
* @// TODO: 2018/4/27 redis fastjson序列化
*/
@Bean
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
//使用fastjson序列化
FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
// 全局开启AutoType,不建议使用
// ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
// 建议使用这种方式,小范围指定白名单
ParserConfig.getGlobalInstance().addAccept("com.developlee.models.");
// value值的序列化采用fastJsonRedisSerializer
template.setValueSerializer(fastJsonRedisSerializer);
template.setHashValueSerializer(fastJsonRedisSerializer);
// key的序列化采用StringRedisSerializer
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setConnectionFactory(redisConnectionFactory);
return template;
} @Bean
@ConditionalOnMissingBean(StringRedisTemplate.class)
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
} /**
* @return
* @// TODO: 2018/4/27 设置redis 缓存时间 5 分钟
*/
@Bean
public RedisCacheConfiguration redisCacheConfiguration() {
FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig();
configuration = configuration.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(fastJsonRedisSerializer)).entryTtl(Duration.ofMinutes(5));
return configuration;
}
}

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

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

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

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

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

精通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. Linux中vim编辑器的缩进的功能键

    vim编程时,经常需要对代码进行缩进处理,以增加程序的可读性和后期的代码维护. 可以采用多种方式达到缩进的目的: 1) 命令模式(command mode) 2) Visual模式(visual mo ...

  2. json数据前台解析 修改check属性用prop()

    jQuery中的$.getJSON( )方法函数主要用来从服务器加载json编码的数据,它使用的是GET HTTP请求.使用方法如下: $.getJSON( url [, data ] [, succ ...

  3. JSP标签和JSTL标签注意点

    1.转发和重定向问题 当前项目:/Test 转发路径:"/"根目录表示当前项目"/Test","/login.jsp"就是"/Te ...

  4. Oracle11G的用户解锁、卸载以及基础操作

    Oracle用户解锁 [以下操作,必须以超级管理员身份登录,才能修改]oracle安装后,会默认生成很多个用户 以超级管理员身份登录,请注意,其中的空格符:[ sys是一个超级管理员,有最大的权限,d ...

  5. 360或其他双核浏览器下在兼容模式用chrome内核渲染的方法

    <meta name="renderer" content="webkit"> <meta http-equiv="X-UA-COM ...

  6. C 碎片四 流程控制

    前面介绍了程序中用到的一些基本要素(常量,变量,运算符,表达式),他们是构成程序的基本成分,下面将介绍C语言中流程控制的三种结构:顺序结构.分支结构.循环结构 一.顺序结构 顺序结构的程序设计是最简单 ...

  7. 安卓usb数据接收

    之前在论坛里面求助了关于监听数据接收的问题,因为第一次做这方面,可能我提的问题太简单了,大神都不愿意回答我,(之前的帖子)晚上FQ浏览网站发现问题的解决办法, 原文是:最近老板让弄安卓和一块板子通信, ...

  8. jar 压缩 解压 war包

    Win+R 输入cmd进入命令行,进入到源码所在目录.所用工具,jdk自带的jar.exe 打包命令:jar -cvf xxx.war * 解包命令: jar -xvf xxx.war * 参数 说明 ...

  9. pscp no such file or directory

    背景:在WINDOWS10 上传一个文件 到 Centos 7中 工具:pscp 用法: pscp.exe -C e:\tinyfox\site\wwwroot\cdms\projecttemplat ...

  10. 页面中引入百度地图,实例化后影响html5的表单元素date的上下箭头

    复现步骤: 使用百度地图的JavaScript的API,引入文件地址"http://api.map.baidu.com/api?key=&v=1.1&services=tru ...