精通SpringBoot--整合Redis实现缓存
今天我们来讲讲怎么在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实现缓存的更多相关文章
- springBoot整合redis(作缓存)
springBoot整合Redis 1,配置Redis配置类 package org.redislearn.configuration; import java.lang.reflect.Method ...
- SpringBoot整合Redis案例缓存首页数据、缓解数据库压力
一.硬编码方式 1.场景 由于首页数据变化不是很频繁,而且首页访问量相对较大,所以我们有必要把首页数据缓存到redis中,减少数据库压力和提高访问速度. 2.RedisTemplate Jedis是R ...
- SpringBoot整合Redis、mybatis实战,封装RedisUtils工具类,redis缓存mybatis数据 附源码
创建SpringBoot项目 在线创建方式 网址:https://start.spring.io/ 然后创建Controller.Mapper.Service包 SpringBoot整合Redis 引 ...
- SpringBoot 整合 Redis缓存
在我们的日常项目开发过程中缓存是无处不在的,因为它可以极大的提高系统的访问速度,关于缓存的框架也种类繁多,今天主要介绍的是使用现在非常流行的NoSQL数据库(Redis)来实现我们的缓存需求. Spr ...
- Redis-基本概念、java操作redis、springboot整合redis,分布式缓存,分布式session管理等
NoSQL的引言 Redis数据库相关指令 Redis持久化相关机制 SpringBoot操作Redis Redis分布式缓存实现 Resis中主从复制架构和哨兵机制 Redis集群搭建 Redis实 ...
- SpringBoot整合Redis、ApachSolr和SpringSession
SpringBoot整合Redis.ApachSolr和SpringSession 一.简介 SpringBoot自从问世以来,以其方便的配置受到了广大开发者的青睐.它提供了各种starter简化很多 ...
- SpringBoot整合Redis及Redis工具类撰写
SpringBoot整合Redis的博客很多,但是很多都不是我想要的结果.因为我只需要整合完成后,可以操作Redis就可以了,并不需要配合缓存相关的注解使用(如@Cacheable). ...
- springboot整合redis(注解形式)
springboot整合redis(注解形式) 准备工作 springboot通常整合redis,采用的是RedisTemplate的形式,除了这种形式以外,还有另外一种形式去整合,即采用spring ...
- springboot整合redis——redisTemplate的使用
一.概述 相关redis的概述,参见Nosql章节 redisTemplate的介绍,参考:http://blog.csdn.net/ruby_one/article/details/79141940 ...
- 九、springboot整合redis二之缓冲配置
1.创建Cache配置类 @Configuration @EnableCaching public class RedisCacheConfig extends CachingConfigurerSu ...
随机推荐
- Git把旧仓库的分支拉到新仓库中
背景:项目新建了个git仓库(B仓库),放改版的新项目,现在运维所有项目构建都是在一个Jenkins里构建,然后拉镜像到相应服务器里,为了不让运维每次构建不同项目需要改git仓库地址,需要把原来项目仓 ...
- Docker | 第四章:Dockerfile简单介绍及使用
前言 前一章节,介绍了Docker常用的命令.在基本使用上,熟悉这些常用的命令基本上就够了.但在一些场景下,比如在部署SpringBoot应用时,通常我们都是打成Jar包,然后利用java命令进行运行 ...
- springboot mybatis 自动生成代码(maven+IntelliJ IDEA)
1.在pom文件中加入需要的依赖(mybatis-generator-core) 和 插件(mybatis-generator-maven-plugin) <dependency> < ...
- Unity中的输入
目录 移动平台的输入 触摸 触摸相关的函数 触摸的一个示例 重力加速器 在Unity中访问重力加速器的信息 重力加速器示例 虚拟键盘 其他输入 传统的输入 鼠标,键盘,控制杆,手柄 虚拟控制轴(Vir ...
- uLua学习之创建游戏对象(二)
前言 上节,刚刚说到创建一个“HelloWorld”程序,大家想必都对uLua有所了解了,现在我们一步步地深入学习.在有关uLua的介绍中(在这里),我们可以发现它使用的框架是Lua + LuaJIT ...
- sublimetext3安装配置
官网:http://www.sublimetext.com/ 中文官网:http://www.sublimetextcn.com/ 包管理器:https://packagecontrol.io/ins ...
- zabbix中监控项报错
报错信息: zabbix报错(Not all processes could be identified, non-owned process info will not be shown, you ...
- LeetCode 4Sum 4个数之和
题意:这是继2sum和3sum之后的4sum,同理,也是找到所有4个元素序列,满足他们之和为target.以vector<vector<int>>来返回,也就是二维的,列长为4 ...
- mongodb索引 全文索引
全文索引,也叫文本索引,平时,我们百度的搜索,比如api文档的搜索,这种全局的索引就可以使用全文索引实现 全文索引:对字符串与字符串数组创建全文可搜索对索引 使用情况:比如有一个数据集合,存储了用户的 ...
- Flutter /bin/sh: /packages/flutter_tools/bin/xcode_backend.sh: No such file or directory
自己写项目中遇到的一个问题, 可以出来是路径找不到,应该是FLUTTER_ROOT这个全局变量没有取到值的原因 1.检查xcode_backend.sh 是否真的存在 2.网上说的:Target -& ...