当前位置: 首页 > news >正文

Spring Boot 3.X 下Redis缓存的尝试(一):初步尝试

背景

        想像一下有这么一个场景,一个系统有超多角色、角色下有多个菜单、菜单下有多个按钮权限,这种子父级关系查询每次向数据库查询相当耗时,那么我们是否可以将这种更新频次不高,而查询耗时的数据且不直接影响业务的数据放进缓存中去,相关查询直接去缓存里去查,减少对数据库的压力,那么Redis是一个不错的选择。

        当然Spring Boot 不采用Redis也可以实现缓存,但是作为开发要想项目中的解耦性,所以针对Redis做个尝试教程供大家讨论。

准备

        安装Redis,看我之前的教程《Ubuntu 系统、Docker配置、Docker的常用软件配置(下)》

基本测试

1.创建Spring Boot 项目

        pom 文件

        

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.5.0</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.example</groupId><artifactId>demo</artifactId><version>0.0.1-SNAPSHOT</version><name>demo</name><description>demo</description><url/><licenses><license/></licenses><developers><developer/></developers><scm><connection/><developerConnection/><tag/><url/></scm><properties><java.version>17</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><configuration><annotationProcessorPaths><path><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></path></annotationProcessorPaths></configuration></plugin><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><excludes><exclude><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></exclude></excludes></configuration></plugin></plugins></build></project>

        项目配置文件

        

spring:data:redis:host: 127.0.0.1port: 6379password: 24568096@qq.comconnect-timeout: 5stimeout: 5smvc:pathmatch:matching-strategy: ant_path_matcher
server:port: 9999

2.Redis配置类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.StringRedisSerializer;@Configuration
public class RedisConfig {@Beanpublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {RedisTemplate<String, Object> template = new RedisTemplate<>();template.setConnectionFactory(factory);// 设置键(key)的序列化器为 StringRedisSerializer,确保键以直观的字符串形式存储template.setKeySerializer(new StringRedisSerializer());// 设置值(value)的序列化器为 StringRedisSerializer,确保值也以字符串形式存储template.setValueSerializer(new StringRedisSerializer());// 初始化模板配置template.afterPropertiesSet();return template;}
}

3.测试


import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.types.RedisClientInfo;import java.util.Collections;
import java.util.List;@SpringBootTest
class DemoApplicationTests {@Autowiredprivate RedisTemplate<String, Object> redisTemplate;@Autowiredprivate RedisService redisService;@Testvoid contextLoads() {redisTemplate.opsForValue().set("name", "张三");String  name = (String) redisTemplate.opsForValue().get("name");System.out.println(name);//----------写入ListredisTemplate.opsForList().leftPush("list", "王王");redisTemplate.opsForList().leftPush("list", "李四");redisTemplate.opsForList().leftPush("list", "赵六");//  获取listList<Object> list = redisTemplate.opsForList().range("list", 0, -1);System.out.println(list);//-----------写入集合redisTemplate.opsForSet().add("set", "张三");redisTemplate.opsForSet().add("set", "李四");redisTemplate.opsForSet().add("set", "王王");redisTemplate.opsForSet().add("set", "赵六");//-----------写入集合List<Object> set = Collections.singletonList(redisTemplate.opsForSet().members("set"));System.out.println(set);//-----------写入MapredisTemplate.opsForHash().put("map", "name", "张三");redisTemplate.opsForHash().put("map", "age", "18");//-----------获取MapList<Object> map = Collections.singletonList(redisTemplate.opsForHash().entries("map"));System.out.println(map);}@Testvoid testRedisService() {redisService.getStuById(1);}}

效果

下一篇:《Spring Boot 3.X 下Redis缓存的尝试(二):自动注解实现自动化缓存操作》

http://www.lqws.cn/news/76717.html

相关文章:

  • Oracle授权操作
  • Mysql备份
  • 【MySQL】视图与用户管理
  • isp中的 ISO代表什么意思
  • Android Studio 配置之gitignore
  • 平滑技术(数据处理,持续更新...)
  • JAVA学习-练习试用Java实现“PCA(主成分分析) :用于降维和数据可视化”
  • DeepSeek模型安全部署与对抗防御全攻略
  • DAY43打卡
  • 力扣LeetBook数组和字符串--数组简介
  • 力扣HOT100之动态规划:32. 最长有效括号
  • 20250602在荣品的PRO-RK3566开发板的Android13下的uboot启动阶段配置BOOTDELAY为10s
  • 代码随想录算法训练营第四天| 242.有效的字母异位词 、 349. 两个数组的交集 、 202. 快乐数 、1. 两数之和
  • 5.RV1126-OPENCV 图形计算面积
  • Android基于LiquidFun引擎实现软体碰撞效果
  • android binder(二)应用层编程实例
  • 循序渐进 Android Binder(一):IPC 基本概念和 AIDL 跨进程通信的简单实例
  • 基于 Android 和 JBox2D 的简单小游戏
  • 实验一:PyTorch基本操作实验
  • 力扣热题100之对称二叉树
  • LeetCode 热题 100 394. 字符串解码
  • C#项目07-二维数组的随机创建
  • CppCon 2014 学习:Exception-Safe Coding
  • Python----目标检测(《YOLOv3:AnIncrementalImprovement》和YOLO-V3的原理与网络结构)
  • Python----目标检测(训练YOLOV8网络)
  • FreeBSD 14.3 候选版本附带 Docker 镜像和关键修复
  • 嵌入式鸿蒙开发环境搭建操作方法与实现
  • web架构3------(nginx的return跳转,gzip压缩,目录浏览,访问控制和location符号优先级)
  • 分布式锁剖析
  • 2025/6月最新Cursor(0.50.5版本)一键自动更换邮箱无限续杯教程