新闻详情

新闻详情

首页 / 资讯中心 / 详情

八. Spring Boot2 整合连接 Redis(超详细剖析)

发布时间:2026/8/31 16:40:49来源:尧图网络
八. Spring Boot2 整合连接 Redis(超详细剖析)
八. Spring Boot2 整合连接 Redis(超详细剖析)---------------------------------#### 文章目录* 八. Spring Boot2 整合连接 Redis(超详细剖析)* 2. 注意事项和细节* 3. 最后* *在 springboot 中 , 整合 redis可以通过 RedisTemplate 完成对 redis 的操作, 包括设置数据/获取数据比如添加和读取数据具体整合实现1. 创建 Maven 项目2. 在 pom.xml 文件当中导入相关的 jar 依赖。如下?xml version1.0 encodingUTF-8? 4.0.0 org.springframework.boot spring-boot-starter-parent 2.6.6 com.rainbowsea redis_springboot 1.0-SNAPSHOT java.version1.8/java.version org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-data-redis org.apache.commons commons-pool2 org.springframework.boot spring-boot-starter-test test com.fasterxml.jackson.core jackson-databind 2.13.2.2 org.springframework.boot spring-boot-maven-plugin 3. 在 resources 目录下创建 application.properties完成 redis 的基本配置如下所示#Redis 服务器地址 spring.redis.host192.168.76.145 #Redis 服务器连接端口 spring.redis.port6379 #Redis 如果有密码,需要配置, 没有密码就不要写 spring.redis.passwordrainbowsea #Redis 数据库索引默认为 0 spring.redis.database0 #连接超时时间毫秒 spring.redis.timeout1800000 #连接池最大连接数使用负值表示没有限制 spring.redis.lettuce.pool.max-active20 #最大阻塞等待时间(负数表示没限制) spring.redis.lettuce.pool.max-wait-1 #连接池中的最大空闲连接 spring.redis.lettuce.pool.max-idle5 #连接池中的最小空闲连接 spring.redis.lettuce.pool.min-idle0 4. 创建/定义一个 Redis 配置类。这个 Redis 配置类是对要使用 RedisTemplate bean 对象的配置可以理解成是一个常规配置。* 和我们以前学过的一个JdbcTemplate的设计理念类似。* 如果不是配置那么 Spring boot 会使用默认配置这个默认配置会出现一些问题比如redisTemplate 的 key 序列化等问题所以通常我们需要配置这个。Redis 配置类.创建 edis_springbootsrcmainjavacom ainbowsea edisconfig RedisConfig.java 配置类package com.rainbowsea.redis.config; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Configuration; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializationContext; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; import java.time.Duration; EnableCaching // 配置开启缓存 Configuration // 定义配置类 public class RedisConfig extends CachingConfigurerSupport { Bean public RedisTemplateString, Object redisTemplate(RedisConnectionFactory factory) { RedisTemplateString, Object template new RedisTemplate(); System.out.println(“template” template); RedisSerializer redisSerializer new StringRedisSerializer(); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.activateDefaultTyping( LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY); jackson2JsonRedisSerializer.setObjectMapper(om); template.setConnectionFactory(factory); // key 序列化方式 template.setKeySerializer(redisSerializer); // value 序列化 template.setValueSerializer(jackson2JsonRedisSerializer); // value hashmap 序列化 template.setHashValueSerializer(jackson2JsonRedisSerializer); return template; } Bean public CacheManager cacheManager(RedisConnectionFactory factory) { RedisSerializer redisSerializer new StringRedisSerializer(); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer new Jackson2JsonRedisSerializer(Object.class); //解决查询缓存转换异常的问题 ObjectMapper om new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.activateDefaultTyping( LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY); jackson2JsonRedisSerializer.setObjectMapper(om); // 配置序列化解决乱码的问题,过期时间 600 秒 RedisCacheConfiguration config RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofSeconds(600)) .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer)) .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)) .disableCachingNullValues(); RedisCacheManager cacheManager RedisCacheManager.builder(factory) .cacheDefaults(config) .build(); return cacheManager; } } 5. 创建 controller 访问设置/获取到 Redis 数据库当中的数据。重点我们这里的RedisTemplate模板对象就是已经配置好了 Jedis 的连接上 Redis的一个模板该模板提供了很多我们操作 Redis 数据库的方法。就和我们前面学习 MySQL 操作连接 MySQL 当中的 JdbcTemplate 模板是类似的。如下所示package com.rainbowsea.redis.controller; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; RestController RequestMapping(“/redisTest”) public class RedisTestController { // 装配 RedisTemplate Resource private RedisTemplate redisTemplate; // 编写一个测试方法 // 演示设置数据和获取数据 GetMapping(“/t1”) public String t1() { // 设置值到 redis 当中,opsForValue 是操作 string 字符串的 redisTemplate.opsForValue().set(“book”, “天龙八部”); // 从 redis 当中获取值 String book (String) redisTemplate.opsForValue().get(“book”); return book; } } 6. 创建场景启动器。package com.rainbowsea.redis; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; SpringBootApplication public class RedisSpringBootApplication { public static void main(String[] args) { SpringApplication.run(RedisSpringBootApplication.class, args); } } 7. 启动程序run, 打开浏览器地址栏上输入http://localhost:9090/redisTest/t1 。在这里插入图片描述* ***演示如何操作 List **package com.rainbowsea.redis.controller; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import java.util.List; RestController RequestMapping(“/redisTest”) public class RedisTestController { // 装配 RedisTemplate Resource private RedisTemplate redisTemplate; // 演示如何操作 list 列表 GetMapping(“/t2”) public String t2() { // list-存 redisTemplate.opsForList().leftPush(“books”, “笑傲江湖”); redisTemplate.opsForList().leftPush(“books”, “hello world”); // list - 取数据 List books redisTemplate.opsForList().range(“books”, 0, -1); String booksList “”; for (Object book : books) { System.out.println(“book-” book.toString()); booksList book.toString(); } return booksList; } // 编写一个测试方法 // 演示设置数据和获取数据 GetMapping(“/t1”) public String t1() { // 设置值到 redis 当中,opsForValue 是操作 string 字符串的 redisTemplate.opsForValue().set(“book”, “天龙八部”); // 从 redis 当中获取值 String book (String) redisTemplate.opsForValue().get(“book”); return book; } }演示如何操作 hashRestController RequestMapping(“/redisTest”) public class RedisTestController { // 装配 RedisTemplate Resource private RedisTemplate redisTemplate; GetMapping(“/t3”) public String t3() { // hash - 存数据 redisTemplate.opsForHash(); // 操作 Zset 有序集合 redisTemplate.opsForZSet(); // 操作 set 集合 redisTemplate.opsForSet(); return null; } 2. 注意事项和细节-----------1. 如果没有提供 RedisConfig 配置类 , springboot 会使用默认配置 也可以使用。但是会存在问题。比如 redisTemplate 模糊查找 key 数据为空。测试 这里我们先将 我们配置的 RedisConfig 配置类注释掉。 编写一个方法获取所有的 key:*表示获取所有的 key RestController RequestMapping(“/redisTest”) public class RedisTestController { // 装配 RedisTemplate Resource private RedisTemplate redisTemplate; // 编写一个方法获取所有的 key GetMapping(“/t3”) public String t3() { Set keys redisTemplate.keys(); for (Object key : keys) { System.out.println(“key --” key.toString()); } return “OK”; } } **当我们将我们的配置的 RedisConfig 类打开不使用 Spring Boot 默认的配置。则不会出现该空的情况。 ** 2.Unrecognized token beijing: was expecting (true, false or null)看报错是 jason 转换异常实际上是因为 redisTemplate 在做数据存储的时候会把存储的内容序列化所以redisTemplate 读取的时候也会反序列化而在 redis 客户端 set 的时候并不会做序列化因此 set 的进去的值在用 redisTemplate 读的时候就会报类 型转换异常了。演示 我们在 Redis 命令行客户端(不通过Java程序的方式)创建 一个 k100的字符串。 然后我们再通过Java程序获取到该(Redis命令行客户端)所创建的 k100 字符串的数据。 解决这个com.fasterxml.jackson.core.JsonParseException也简单既然我们 Resi 命令行客户端(创建的 对象信息/值)不会被序列化那我们就不用 Redis 命令行客户端创建对象了直接就是。我们想用Java程序当中反序化的功能我们就用 Java程序创建对象/值同时也用Java程序获取对象的数据。存和取都保持一致都是在Java程序当中即可(因为Java程序创建的对象会自行序列化的)。这里就不演示了因为我们上述的所有操作都是Java程序连接 Redis 创建对象也是Java程序获取数据。都是没问题的。3. 最后------- “在这个最后的篇章中我要表达我对每一位读者的感激之情。你们的关注和回复是我创作的动力源泉我从你们身上吸取了无尽的灵感与勇气。我会将你们的鼓励留在心底继续在其他的领域奋斗。感谢你们我们总会在某个时刻再次相遇。”
网站建设高端定制企业官网
RELATED

相关资讯

更多精彩内容,欢迎继续阅读

较早相关资讯

最新相关资讯

AI数据中心规划指南:功率密度、散热与网络运维的关键挑战 2026/8/31 17:21:02

AI数据中心规划指南:功率密度、散热与网络运维的关键挑战

先给一个判断:AI 数据中心真正让工程团队头疼的,从来不是“又多买了几块 GPU”,而是电、热、网络和运维模式这四个维度,几乎全部要和传统数据中心反着来。 过去几年,很多团队在推进 AI 基础设施时,习惯沿用…

阅读更多 →
刷机全流程SD-eMMC-单分区—【万物智能之开源鸿蒙OpenHarmony系统实战开发系列教程】 2026/8/31 17:21:02

刷机全流程SD-eMMC-单分区—【万物智能之开源鸿蒙OpenHarmony系统实战开发系列教程】

镜像在手里了。今天专门写怎么刷:SD 卡、eMMC 线刷、只更新某一个分区。路径写错时工具会显示成功,分区却纹丝不动。 dd 打印了 10 records in,md5sum 跟镜像一致,复位之后 /proc/version 还是三天前。下一次更干净:dd…

阅读更多 →
纯碱库存分析实战:Python自动检测累库周期与数据可视化 2026/8/31 17:21:02

纯碱库存分析实战:Python自动检测累库周期与数据可视化

做商品基本面研究时,库存数据往往是判断供需节奏最直接的“体温计”。尤其是纯碱这类强周期性品种,库存连续累加往往意味着下游拿货意愿弱、供应端过剩压力正在兑现。但真正折磨人的是:官方网站和资讯平台的数据格式五花八门,发布…

阅读更多 →
开源物联网管理系统源码实战:号卡智能管理平台与轻量级业务支撑 2026/8/31 17:21:02

开源物联网管理系统源码实战:号卡智能管理平台与轻量级业务支撑

简介:这是一套面向物联网业务开发者与中小型企业技术团队的轻量级综合支撑平台源码,聚焦号卡与模组全生命周期管理,解决多运营商物联网卡分散运维、资费结算复杂、设备状态难监控等实际问题。资源包共2000个文件,含1099个Java后端…

阅读更多 →
AI生成C++代码能否上生产?质量拆解与工程实践指南 2026/8/31 17:21:02

AI生成C++代码能否上生产?质量拆解与工程实践指南

先聊一个大家都很关心的问题:AI 代码生成到底能不能直接用到生产环境的 C 项目里?C 这个语言有点特殊,它不像 Python 那样改完立刻能跑,也不像 Go 那样编译一次就能得到静态二进制。C 的构建系统多、依赖复杂、内存管理靠手、并发…

阅读更多 →
列车试验场播放音乐:从信号选择到声学测试的系统工程 2026/8/31 17:16:00

列车试验场播放音乐:从信号选择到声学测试的系统工程

“在列车靶场上我放的音乐。” 第一次看到这个标题,大概率会以为是一句随手写的随笔,背后可能是某个生活场景的碎片。但放到工程语境里,它完全可以是一个项目代号:在列车的试验场地里,用一段音乐作为标准信号&#xff…

阅读更多 →

今日资讯

本周资讯

本月资讯

看完文章仍有疑问?

联系尧图顾问,获取一对一建站咨询

立即免费咨询 📞 400-888-8888
📞