springboot整合redis缓存一些知识点
前言
最近在做智能家居平台,考虑到家居的控制需要快速的响应于是打算使用redis缓存。一方面减少数据库压力另一方面又能提高响应速度。项目中使用的技术栈基本上都是大家熟悉的springboot全家桶,在springboot2.x以后操作redis的客户端推荐使用lettuce(生菜)取代jedis。
jedis的劣势主要在于直连redis,又无法做到弹性收缩。
一、配置文件
application.yml文件中的内容
spring:
application:
name: simple-lettuce
cache:
type: redis
redis:
# 缓存超时时间ms
time-to-live:
# 是否缓存空值
cache-null-values: true
redis:
host: 127.0.0.1
port:
password:
# 连接超时时间(毫秒)
timeout:
# Redis默认情况下有16个分片,这里配置具体使用的分片,默认是0
database:
# spring2.x redis client 采用了lettuce(生菜),放弃使用jedis
lettuce:
# 关闭超时时间
shutdown-timeout:
pool:
# 连接池最大连接数(使用负值表示没有限制) 默认
max-active:
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -
max-wait: -
# 连接池中的最大空闲连接 默认
max-idle:
# 连接池中的最小空闲连接 默认
min-idle:
说明:
- spring.cache.type: redis
已经表明使用项目采用redis做为缓存方式。
- spring.cache.redis.cache-null-values: true
表示是否缓存空值,一般情况下是允许的。因为这涉及到缓存的三大问题:缓存穿透、缓存雪崩、缓存击穿。
如果设置false即不允许缓存空值,这样会导致很多请求数据库没有的数据时,不会缓存到redis导致每次都会请求到数据库。这种情况即:缓存穿透。
具体想初步了解这些概念可以参考文章:缓存三大问题及解决方案!
二、config配置类
@Configuration
@EnableCaching
public class RedisTemplateConfig extends CachingConfigurerSupport { private static Map<String, RedisCacheConfiguration> cacheMap = Maps.newHashMap(); @Bean(name = "stringRedisTemplate")
@ConditionalOnMissingBean(name = "stringRedisTemplate") //表示:如果容器已经有redisTemplate bean就不再注入
public StringRedisTemplate stringRedisTemplate(LettuceConnectionFactory redisConnectionFactory) {return new StringRedisTemplate(redisConnectionFactory);
} @Bean(name = "redisTemplate")
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
System.out.println("RedisTemplateConfig.RedisTemplate");
RedisTemplate<String, Object> template = new RedisTemplate<>();
// key的序列化采用StringRedisSerializer
template.setKeySerializer(keySerializer());
template.setHashKeySerializer(keySerializer());
// value值的序列化采用fastJsonRedisSerializer
template.setValueSerializer(valueSerializer()); //使用fastjson序列化
template.setHashValueSerializer(valueSerializer()); //使用fastjson序列化
template.setConnectionFactory(lettuceConnectionFactory);
return template;
} /**
* 添加自定义缓存异常处理
* 当缓存读写异常时,忽略异常
* 参考:https://blog.csdn.net/sz85850597/article/details/89301331
*/
@Override
public CacheErrorHandler errorHandler() {
return new IgnoreCacheErrorHandler();
} @SuppressWarnings("Duplicates")
@Bean
@Primary//当有多个管理器的时候,必须使用该注解在一个管理器上注释:表示该管理器为默认的管理器
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
// 默认配置
RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
.serializeKeysWith(keyPair())
.serializeValuesWith(valuePair())
.entryTtl(Duration.ofSeconds(DEFAULT_TTL_SECS)) //设置过期时间
.disableCachingNullValues(); // 其它配置
for(MyCaches cache : MyCaches.values()) {
cacheMap.put(cache.name(),
RedisCacheConfiguration.defaultCacheConfig()
.serializeKeysWith(keyPair())
.serializeValuesWith(valuePair())
.entryTtl(cache.getTtl())
// .disableCachingNullValues() // 表示不允许缓存空值
.disableKeyPrefix() // 不使用默认前缀
// .prefixKeysWith("mytest") // 添加自定义前缀
);
} /** 遍历MyCaches添加缓存配置*/
RedisCacheManager cacheManager = RedisCacheManager.builder(
RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory)
)
.cacheDefaults(defaultCacheConfig)
.withInitialCacheConfigurations(cacheMap)
.transactionAware()
.build(); ParserConfig.getGlobalInstance().addAccept("mypackage.db.entity.");
return cacheManager;
} /**
* key序列化方式
* @return
*/
private RedisSerializationContext.SerializationPair<String> keyPair() {
RedisSerializationContext.SerializationPair<String> keyPair =
RedisSerializationContext.SerializationPair.fromSerializer(keySerializer());
return keyPair;
} private RedisSerializer<String> keySerializer() {
return new StringRedisSerializer();
} /**
* value序列化方式
* @return
*/
private RedisSerializationContext.SerializationPair<Object> valuePair() {
RedisSerializationContext.SerializationPair<Object> valuePair =
RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer());
return valuePair;
} /**
* 使用fastjson序列化
* @return
*/
private RedisSerializer<Object> valueSerializer() {
MyFastJsonRedisSerializer<Object> fastJsonRedisSerializer = new MyFastJsonRedisSerializer<>(Object.class);
return fastJsonRedisSerializer;
} @Getter
private enum MyCaches {
defaultCache(Duration.ofDays(1)),
MyCaches(Duration.ofMinutes(10)); MyCaches(Duration ttl) {
this.ttl = ttl;
}
/** 失效时间 */
private Duration ttl = Duration.ofHours(1);
}
}
说明
1. 类上的注解@EnableCaching
表明开启缓存功能。
2. extends CachingConfigurerSupport
这个类就很丰富了,其实如果没有什么特别操作也可以不用继承这个类。
这个类可以支持动态选择缓存方式,比如项目中不止一种缓存方案,有可能有ehcache那么可以自定义在什么情况下使用redis使用情况下使用ehcache。还有一些有关异常的处理。我也不是很懂具体可以参考:
3. StringRedisTemplate和RedisTemplate的使用
三、缓存注解使用
@Cacheable 使用在查询方法上
@CachePut 使用在更新、保存方法上
@CacheEvict 使用在删除方法上
需要注意的是@Cacheable、@CachePut方法一定要有返回被缓存对象。因为注解使用的AOP切面如果没有返回值表示缓存对象为空值。
@CacheConfig注解在类上,可以选择使用哪个缓存、缓存管理器、Key生成器
好了以上就是最近在项目中的一些知识点总结,如果以后使用缓存有新的体会我会同步更新的。
springboot整合redis缓存一些知识点的更多相关文章
- SpringBoot 整合 Redis缓存
在我们的日常项目开发过程中缓存是无处不在的,因为它可以极大的提高系统的访问速度,关于缓存的框架也种类繁多,今天主要介绍的是使用现在非常流行的NoSQL数据库(Redis)来实现我们的缓存需求. Spr ...
- springboot整合redis缓存
使用springBoot添加redis缓存需要在POM文件里引入 org.springframework.bootspring-boot-starter-cacheorg.springframewor ...
- SpringBoot整合redis缓存(一)
准备工作 1.Linux系统 2.安装redis(也可以安装docker,然后再docker中装redis,本文章就直接用Linux安装redis做演示) redis下载地址: 修改redis,开启远 ...
- SpringBoot缓存管理(二) 整合Redis缓存实现
SpringBoot支持的缓存组件 在SpringBoot中,数据的缓存管理存储依赖于Spring框架中cache相关的org.springframework.cache.Cache和org.spri ...
- SpringBoot入门系列(七)Spring Boot整合Redis缓存
前面介绍了Spring Boot 中的整合Mybatis并实现增删改查,.不清楚的朋友可以看看之前的文章:https://www.cnblogs.com/zhangweizhong/category/ ...
- springBoot整合redis(作缓存)
springBoot整合Redis 1,配置Redis配置类 package org.redislearn.configuration; import java.lang.reflect.Method ...
- SpringBoot整合Redis、mybatis实战,封装RedisUtils工具类,redis缓存mybatis数据 附源码
创建SpringBoot项目 在线创建方式 网址:https://start.spring.io/ 然后创建Controller.Mapper.Service包 SpringBoot整合Redis 引 ...
- 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简化很多 ...
随机推荐
- docker 安装redis 并配置外网可以访问
1, docker 拉去最新版本的redis docker pull redis #后面可以带上tag号, 默认拉取最新版本 2, docker安装redis container 安装之前去定义我们的 ...
- SSIM (Structural SIMilarity) 结构相似性
公式基于样本x和 y 之间的三个比较衡量:亮度 (luminance).对比度 (contrast) 和结构 (structure). 每次计算的时候都从图片上取一个 N*N的窗口,然后不断滑动窗口进 ...
- github资源汇总
github免费的编程中文书籍索引 机器学习(Machine Learning)&深度学习(Deep Learning)资料(Chapter 1) Python 资源大全中文版
- idea 报错javax/xml/bind/DatatypeConverter
idea 报错javax/xml/bind/DatatypeConverter java.lang.NoClassDefFoundError: javax/xml/bind/DatatypeCon ...
- ISO/IEC 9899:2011 条款6.7.2——类型说明符
6.7.2 类型说明符 语法 1.type-specifier: void char short int long float double signed unsigned _Bool _Comple ...
- pytorch如何先初始化变量,然后再赋值
下面是定义初始化 #初始化输入的张量 - torch.empty是返回一个包含未初始化数据的张量 self.input = torch.empty(size=(self.opt.batchsize, ...
- 004-行为型-06-命令模式(Command)
一.概述 是一种数据驱动的设计模式 请求以命令的形式包裹在对象中,并传给调用对象.调用对象寻找可以处理该命令的合适的对象,并把该命令传给相应的对象,该对象执行命令. 将请求封装成对象,以便使用不同的请 ...
- Django之密码加密
通过django自带的类库,来加密解密很方便,下面来简单介绍下: 导入包: from django.contrib.auth.hashers import make_password, check_p ...
- Linux strace追踪命令详解
strace介绍 strace命令是一个集诊断.调试.统计与一体的工具,我们可以使用strace对应用的系统调用和信号传递的跟踪结果来对应用进行分析,以达到解决问题或者是了解应用工作过程的目的.当然s ...
- 【mysql】reset Password
https://www.cnblogs.com/josn1984/p/8550419.html https://blog.csdn.net/l1028386804/article/details/92 ...