Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >spring boot redis 缓存_redis本地缓存

spring boot redis 缓存_redis本地缓存

作者头像
全栈程序员站长
发布于 2022-09-30 09:46:52
发布于 2022-09-30 09:46:52
2.2K00
代码可运行
举报
运行总次数:0
代码可运行

大家好,又见面了,我是你们的朋友全栈君。

SpringBoot 集成 Redis 缓存

查询操作是应用中最常见的操作,如果每次查询都从 MySQL 中查询则会影响效率,通常需要引入缓存来实现查询性能的优化。缓存可以选择本地缓存,远程缓存或本地缓存结合远程缓存。本地缓存可以使用 Guava 或 Caffeine 提供的解决方案,而远程缓存则可以选择 Redis 这样的内存数据库。本文记录一下 SpringBoot 集成 Redis 做缓存的相关配置。

1 引入依赖

引入相应 Starter。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2 缓存配置

SpringBoot 中缓存由 CacheManager 管理,实现自己的 CacheManager 即可。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) { 

RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//解决查询缓存转换异常的问题,为Jackson配置ObjectMapper
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.activateDefaultTyping(
LaissezFaireSubTypeValidator.instance,
ObjectMapper.DefaultTyping.NON_FINAL,
JsonTypeInfo.As.WRAPPER_ARRAY);
om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
jackson2JsonRedisSerializer.setObjectMapper(om);
// 配置序列化(解决乱码的问题)
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
.disableCachingNullValues();
Set<String> cacheNames = new HashSet<>();
cacheNames.add("FlashActivity");
cacheNames.add("FlashItem");
Map<String, RedisCacheConfiguration> configMap = new ConcurrentHashMap<>();
configMap.put("FlashActivity", config.entryTtl(Duration.ofMinutes(60)));
configMap.put("FlashItem", config.entryTtl(Duration.ofSeconds(3)));
return RedisCacheManager.builder(factory)
.cacheDefaults(config)
.initialCacheNames(cacheNames)
.withInitialCacheConfigurations(configMap)
.build();
}

2.1 配置 ObjectMapper

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 必要配置,否则反序列化得到的是LinkedHashMap对象
om.activateDefaultTyping(
LaissezFaireSubTypeValidator.instance,
ObjectMapper.DefaultTyping.NON_FINAL,
JsonTypeInfo.As.WRAPPER_ARRAY);
// 出现未知字段不报错
om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

2.2 配置 CacheConfig

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
// 配置序列化(解决乱码的问题)
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
.disableCachingNullValues();

2.3 不同 Cache 设置不同 TTL

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Set<String> cacheNames = new HashSet<>();
cacheNames.add("FlashActivity");
cacheNames.add("FlashItem");
Map<String, RedisCacheConfiguration> configMap = new ConcurrentHashMap<>();
configMap.put("FlashActivity", config.entryTtl(Duration.ofMinutes(60)));
configMap.put("FlashItem", config.entryTtl(Duration.ofSeconds(3)));

3 注解使用

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
// 类上指定缓存到哪些 Cache
@CacheConfig(cacheNames = "FlashItem")
@CacheEvict(key = "'FlashItemCache'.concat(#itemId)")
// sync指定为true,缓存失效只会有一个线程取请求数据库,其他线程使用请求回的数据
@Cacheable(key = "'ActivityFlashItemCache'.concat(#activityId)", sync = true)

4 RedisTemplate 配置

使用 RedisTemplate 可以实现手动缓存或其他对 Redis 操作,但之前只是配置缓存相关配置,直接使用RedisTemplate 时不会生效,需要单独配置。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { 

RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key-value结构序列化数据结构
redisTemplate.setKeySerializer(stringRedisSerializer);
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
// hash数据结构序列化方式,必须这样否则存hash 就是基于jdk序列化的
redisTemplate.setHashKeySerializer(stringRedisSerializer);
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/192673.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年9月17日 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
SpringBoot使用Redis做缓存结合自带注解
配置Spring Cache <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</a
HUC思梦
2020/09/03
1.5K0
Spring Boot 结合 Redis 的序列化配置
默认情况下,Spring 为我们提供了一个 RedisTemplate 来进行对 Redis 的操作,但是 RedisTemplate 默认配置的是使用Java本机序列化。
Vincent-yuan
2021/10/28
4.2K0
Spring Boot 结合 Redis 的序列化配置
Spring Cache+Redis缓存数据
  我们知道内存的读取速度远大于硬盘的读取速度。当需要重复地获取相同数据时,一次一次地请求数据库或者远程服务,导致在数据库查询或远程方法调用上消耗大量的时间,最终导致程序性能降低,这就是数据缓存要解决的问题。
别团等shy哥发育
2023/02/25
1K0
Spring Cache+Redis缓存数据
【SpringBoot2.0系列08】SpringBoot之redis数据缓存管理
【SpringBoot2.0系列02】SpringBoot之使用Thymeleaf视图模板
yukong
2018/08/20
5840
springboot2.0+redis 二级缓存 乱码问题
SpringCacheRedisConfig import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.
用户5899361
2020/12/07
4961
SpringBoot整合redis
前言 使用注解实现Redis缓存功能的具体代码 1 引入jar包 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> 2 添加配置 spring.redis.host=xxxxxxx spring.redis.port=6379 // 如
在水一方
2022/10/04
3080
springboot缓存之自定义CacheManager
先要说明的是上一节springboot缓存之使用redis作为缓存管理是springboot的旧版本了,最新的springboot2.x已经不这么用了,而且缓存注解一般用于service上,而不是controller上。百度了下整体代码是这样的:MyRedisConfig.java
西西嘛呦
2020/08/26
3.5K0
SpringCache基本配置类
benym
2024/05/18
1070
springboot配置RedisTemplate和RedisCacheManager
1、项目目录结构: 2、application.properties配置文件: 我这里redis连的是虚拟机上面的,你改下host地址就行 spring.datasource.url=jdbc:mysql://localhost:3306/spring_cache spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.cj.jd
别团等shy哥发育
2023/02/25
1.2K0
springboot配置RedisTemplate和RedisCacheManager
springboot实战之nosql整合(redis篇)
关于redis的内容,我之前已经分享过了很多了,今天这篇算是为了springboot nosql整合中的凑数篇吧,哈哈,虽然这么说,但如果点进来了,蛮看下,说不定会有一些新发现
lyb-geek
2019/10/10
8400
Spring Boot 整合 Redis
因为首页接口对应获取的首页数据变化不大,但访问量较大,所以就有必要将首页接口数据缓存到redis缓存中,减少数据库压力和提高访问速度
FHAdmin
2022/03/03
1K0
Spring Boot整合 NoSQL 数据库 Redis
在日常的开发中,除了使用Spring Boot这个企业级快速构建项目的框架之外,随着业务数据量的大幅度增加,对元数据库造成的压力成倍剧增。在此背景下,Redis这个NoSQL数据库已然整个项目架构中的不可或缺的一部分,懂得如何Spring Boot整合 Redis,是当今开发人员必备的一项技能,接下来对整合步骤进行详细说明。
百思不得小赵
2022/12/01
4640
Spring Boot整合 NoSQL 数据库 Redis
Spring Cache解析
本文基于springboot2.3.7版本进行分析,对应的spring-context版本为5.2.12,官方文档地址如下:
程序员小义
2024/04/10
1510
Spring Cache解析
SpringBoot集成Redis缓存
https://www.cnblogs.com/noneplus/p/11532065.html
Noneplus
2019/09/24
6050
SpringBoot集成Redis缓存
Springboot中的redis配置类
简单记录一下 首先依赖: <!-- redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- spring2.X集成redis所需common-pool2-->
Tom2Code
2022/11/21
6900
Mall 电商实战项目发布重大更新,全面支持SpringBoot 2.3.0 !
之前一直使用的是SpringBoot 2.1.7版本,这个版本是2019年8月发布的,距离现在已经一年多了,也到了更新版本的时候了。SpringBoot 2.3.0 是今年5月发布的,还是比较新的版本,想了解这个版本新特性的朋友可以看下《SpringBoot 2.3.0 新特性一览,快来跟我实践一波!》。
macrozheng
2020/08/11
6290
Redis---整合SpringBoot篇
Redis6 1、引入redis相关依赖 2、application.properties配置redis配置 3.添加redis配置类 4.测试一下 RedisTemplate基本使用如下 ---- 1、引入redis相关依赖 <!-- redis的启动器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </depende
大忽悠爱学习
2021/11/15
3000
redis过期监听
今天写拼团功能,如果24小时后还没有人满,则此次拼团就失败了,那么这里我用redis过期监听来实现,键过期去处理订单状态等业务
adu
2022/10/30
2.3K0
redis过期监听
SpringBoot集成Redis引起的序列化问题
想必大家对SpringBoot可能已经很熟悉了,包括集成Redis这种常用的技术,之前一直用一贯的写法去集成Redis,写配置类没发现过任何问题,但是上周在给Redis配置类加了一个Bean之后就出现了很难发现的问题。
一个程序员的成长
2020/11/25
1.5K0
从零搭建Spring Boot脚手架(6):整合Redis作为缓存
上一文我们整合了Mybatis Plus,今天我们会把缓存也集成进来。缓存是一个系统应用必备的一种功能,除了在减轻数据库的压力之外。还在存储一些短时效的数据场景中发挥着重大作用,比如存储用户Token、短信验证码等等,目前缓存的选型还是比较多的,EHCACHE、HAZELCAST、CAFFEINE、COUCHBASE以及本文要整合的REDIS。接下来我们将会在kono脚手架项目中集成Spring Cache以及Redis。
码农小胖哥
2020/08/25
9870
从零搭建Spring Boot脚手架(6):整合Redis作为缓存
相关推荐
SpringBoot使用Redis做缓存结合自带注解
更多 >
领券
💥开发者 MCP广场重磅上线!
精选全网热门MCP server,让你的AI更好用 🚀
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档