精通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 ...
随机推荐
- pat1061. Dating (20)
1061. Dating (20) 时间限制 50 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue Sherlock Holmes ...
- spring数组注入
数组注入 public class MyCollection { private String[]array; private List<String>list; ...
- H5移动端原生长按事件
// 函数名longpress// 参数为: 需长按元素的id.长按之后处理函数func function longPress(id, func,timeout=500) { var timeOutE ...
- VS2008 Pocket PC 2003 SE VGA仿真程序网络设置
最近对这个问题摸索的很久,都没有解决,今天终于搞定,现将大体设置步骤记录下来,以备回顾和方便别人查看,步骤如下: 1.打开VS2008,打开Windows Mobile设备中心(网上有下载). 2.连 ...
- Laravel项目的结构文章
http://esbenp.github.io/2016/04/11/modern-rest-api-laravel-part-1/
- 一、 Spring Cloud Eureka ,咱们先跑起来
一.Spring Cloud 简介 Spring Cloud 是一个基于Spring Boot 实现的微服务架构开发工具.是一个涉及到服务治理.分布式配置管理.负载均衡.服务容错.API网关.消息总线 ...
- $.ajax和$.load的区别
http://lib.csdn.net/article/jquery/35614?knId=646
- The eighth day
time n(名词):时间:次,时代,时刻: vt(及物动词):为...安排时间:测定...的时间:调准(机械的速度): vi(不及物动词):合拍,和谐,打拍子 files (原型是fly) vi(不 ...
- C#值类型、引用类型的区别
在<C#类型简述>http://blog.csdn.net/letnet1981/article/details/48223831,中提到了值类型和引用类型,这里我们就来了解一下它们的区别 ...
- 六、C++离散傅里叶逆变换
C++离散傅里叶逆变换 一.序言: 该教程承接上文的离散傅里叶变换,用于进行离散傅里叶逆变换. 二.设计目标 对复数数组进行离散傅里叶逆变换,并生成可供使用的图像类. 三.详细步骤 输入:经傅里叶变换 ...