Springboot——Redis的使用

在当今的软件开发领域,缓存技术是提升应用性能的关键手段之一。Redis 作为一款高性能的键值对存储数据库,凭借其出色的读写速度和丰富的数据结构,在缓存场景中得到了广泛应用。Spring Boot 作为一款简化 Spring 应用开发的框架,与 Redis 的集成可以让开发者轻松地在项目中使用 Redis 缓存。本文将详细介绍如何在 Spring Boot 项目中集成和使用 Redis。

项目搭建

首先在你的项目中引入redis的Maven依赖确保使用

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

在 application.properties 或 application.yml 中配置 Redis 连接信息。以下是 application.yml 的示例配置:

spring: redis:database: 0           # Redis服务器数据库host: 127.0.0.1       # Redis服务器地址port: 6379            # Redis服务器连接端口password: 123456      # Redis服务器连接密码(默认为空)timeout: 6000         # Redis连接超时时间(毫秒)

Redis 基本操作

配置Redis的配置类

package com.lppaa.redisdemo.config;import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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.core.StringRedisTemplate;
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;
import java.util.HashMap;
import java.util.Map;@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {@Beanpublic CacheManager cacheManager(RedisConnectionFactory factory){RedisSerializer<String> keyRedisSerializer = new StringRedisSerializer(); // redis的key序列化方式Jackson2JsonRedisSerializer valueRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); // redis的value的序列化//解决查询缓存转换异常的问题ObjectMapper om = new ObjectMapper();om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);valueRedisSerializer.setObjectMapper(om);//配置序列化(解决乱码的问题)RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ZERO) // 默认生存时间.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keyRedisSerializer)).serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueRedisSerializer)).disableCachingNullValues();//缓存配置mapMap<String,RedisCacheConfiguration> cacheConfigurationMap=new HashMap<>();//自定义缓存名,后面使用的@Cacheable的CacheNamecacheConfigurationMap.put("myRedis",config);
//        cacheConfigurationMap.put("default",config);RedisCacheManager cacheManager = RedisCacheManager.builder(factory).cacheDefaults(config).withInitialCacheConfigurations(cacheConfigurationMap).build();return cacheManager;}@Beanpublic RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {StringRedisTemplate template = new StringRedisTemplate(factory);Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);ObjectMapper om = new ObjectMapper();om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);jackson2JsonRedisSerializer.setObjectMapper(om);template.setValueSerializer(jackson2JsonRedisSerializer);template.afterPropertiesSet();return template;}}
  • CacheManager方法:负责管理缓存的创建、获取和清理等操作。此方法对 Redis 缓存管理器进行了配置,具体步骤如下:
    • 序列化配置
      • 对 Redis 的键使用 StringRedisSerializer 进行序列化。
      • 对 Redis 的值使用 Jackson2JsonRedisSerializer 进行序列化,同时配置 ObjectMapper 以避免查询缓存时出现转换异常。
    • 缓存配置
      • 借助 RedisCacheConfiguration 配置默认的缓存策略,包含默认生存时间、键和值的序列化方式,并且禁止缓存空值。
      • 创建一个 Map 来存放自定义的缓存配置,这里定义了一个名为 "myRedis" 的缓存。
    • 缓存管理器构建
      • 利用 RedisCacheManager.builder 构建缓存管理器,设置默认缓存配置以及自定义的缓存配置。
  • redisTemplate方法:作用是在代码里对 Redis 进行操作

    • 采用 StringRedisTemplate 作为基础模板,它是 RedisTemplate 的子类,专门用于处理字符串类型的键和值。
    • 同样使用 Jackson2JsonRedisSerializer 对值进行序列化,并且配置 ObjectMapper 以防止查询缓存时出现转换异常。

编写服务层逻辑

EmployeeService接口类
public interface EmployeeService {List<Employee> findAll();Employee findById(Integer id);Employee update(Employee employee);Integer delete(Integer id);}

EmployeeServiceImpl接口实现类

package com.lppaa.redisdemo.service.serviceImpl;import com.lppaa.redisdemo.dao.EmployeeDao;
import com.lppaa.redisdemo.entity.Employee;
import com.lppaa.redisdemo.service.EmployeeService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;import java.util.Collections;
import java.util.Date;
import java.util.List;@Service
public class EmployeeServiceImpl implements EmployeeService {@AutowiredEmployeeDao employeeDao;@Overridepublic List<Employee> findAll() {return employeeDao.findAll();}@Override@Cacheable(cacheNames = "myRedis" ,key = "T(com.lppaa.redisdemo.utils.MD5Utils).md5('EmployeeService_findById' + #id)" ,unless = "#result==null")public Employee findById(Integer id) {System.out.println("进入方法,去数据库查询");return employeeDao.findById(id);}@Override@CachePut(cacheNames = "myRedis", key = "T(com.lppaa.redisdemo.utils.MD5Utils).md5('EmployeeService_findById' + #employee.id)",condition = "#result != null")public Employee update(Employee employee) {employee.setTime(new Date());Integer ans = employeeDao.update(employee);if(ans>0)return employeeDao.findById(employee.getId());return null;//表示更新失败 结果为空 不存入缓存 结果不变}@Override@CacheEvict(cacheNames = "myRedis", key = "T(com.lppaa.redisdemo.utils.MD5Utils).md5('EmployeeService_findById' + #id)")public Integer delete(Integer id) {Integer s = employeeDao.delete(id);return s;}
}
@Cacheable 注解 
  • @Cacheable 注解:用于标记该方法的结果可以被缓存。
    • cacheNames = "myRedis":指定使用名为 myRedis 的缓存,这个缓存名称在 RedisConfig 类中配置。
    • key = "T(com.lppaa.redisdemo.utils.MD5Utils).md5('EmployeeService_findById' + #id)":使用 SpEL(Spring Expression Language)表达式生成缓存的键。这里调用 MD5Utils 类的 md5 方法对 "EmployeeService_findById" 和传入的 id 拼接后的字符串进行 MD5 加密,确保每个不同的 id 对应一个唯一的缓存键。
    • unless = "#result==null":表示如果方法的返回结果为 null,则不将结果存入缓存。
  • 当调用该方法时,Spring 会先检查缓存中是否存在对应的键,如果存在则直接返回缓存中的结果,否则执行方法体中的代码,从数据库中查询数据,并将结果存入缓存。
@CachePut 注解
  • @CachePut 注解:用于更新缓存。无论缓存中是否存在对应的键,都会执行方法体中的代码,并将方法的返回结果存入缓存。
    • cacheNames = "myRedis":指定使用名为 myRedis 的缓存。
    • key = "T(com.lppaa.redisdemo.utils.MD5Utils).md5('EmployeeService_findById' + #employee.id)":生成缓存的键,与 findById 方法使用相同的键生成策略。
    • condition = "#result != null":表示只有当方法的返回结果不为 null 时,才将结果存入缓存。
  • 该方法首先更新员工的时间戳,然后调用 EmployeeDao 的 update 方法更新数据库中的员工信息。如果更新成功,则再次查询数据库获取最新的员工信息并返回,同时更新缓存;如果更新失败,则返回 null,不更新缓存。
CacheEvict 注解
  • @CacheEvict 注解:用于从缓存中移除指定键的缓存项。
    • cacheNames = "myRedis":指定使用名为 myRedis 的缓存。
    • key = "T(com.lppaa.redisdemo.utils.MD5Utils).md5('EmployeeService_findById' + #id)":生成要移除的缓存键,与 findById 和 update 方法使用相同的键生成策略。
  • 该方法调用 EmployeeDao 的 delete 方法从数据库中删除指定 id 的员工信息,并从缓存中移除对应的缓存项。

编写控制层逻辑

package com.lppaa.redisdemo.controller;import com.alibaba.fastjson.JSON;
import com.lppaa.redisdemo.entity.Employee;
import com.lppaa.redisdemo.entity.User;
import com.lppaa.redisdemo.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;import java.util.Date;@RestController
@RequestMapping("/test")
public class RedisController {@Autowiredprivate RedisTemplate redisTemplate;@Autowiredprivate EmployeeService employeeService;@Autowiredprivate StringRedisTemplate stringRedisTemplate;@RequestMapping("/aaa")public String testA(){User user = new User();user.setName("李四");user.setAge(20);
//        redisTemplate.opsForValue().set("user", JSON.toJSONString(user));//redisTemplate.opsForValue().set("ttt", user);stringRedisTemplate.opsForValue().set("qweirj", JSON.toJSONString(user));return "success";}@RequestMapping("/findbyid")@ResponseBodypublic Employee findbyId(Integer id){Employee employee = employeeService.findById(id);return employee;}@RequestMapping("/update")@ResponseBodypublic String update(Employee e){e.setTime(new Date());Employee byId = employeeService.update(e);if(byId != null)return "success";return "false";}@RequestMapping("/delete")@ResponseBodypublic String dete(Integer id){Integer s = employeeService.delete(id);if(s == 1)return "success";return "false";}
}

最后打开Redis即可进行使用。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/80486.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

BEVPoolv2:A Cutting-edge Implementation of BEVDet Toward Deployment

背景 该论文是在BEVDet的基础上进行了一个调整优化&#xff0c;传统的方法是将特征图与深度预测进行外积得到视椎特征图&#xff0c;再将它与预处理好的体素索引结合&#xff0c;将每个视椎特征分类到每个voxel中进行累加和的操作。BEVFusion与BEVDepth等方法是避免了累加和&a…

蓝桥杯常考的找规律题

目录 灵感来源&#xff1a; B站视频链接&#xff1a; 找规律题具有什么样的特点&#xff1a; 报数游戏&#xff08;Java组&#xff09;&#xff1a; 题目描述&#xff1a; 题目链接&#xff1a; 思路详解&#xff1a; 代码详解&#xff1a; 阶乘求和&#xff08;Java组…

使用ffmpeg 将图片合成为视频,填充模糊背景,并添加两段音乐

1.输入3张图片,每张播放一次,播放两秒,视频分辨率设置为1920:1080,每张图片前0.3秒淡入,后0.3秒淡出,图片宽高比不变,用白色填充空白区域 ffmpeg -loop 1 -t 2 -i "img1.jpg" \-loop 1 -t 2 -i "img2.jpg" \-loop 1 -t 2 -i "img3.jpg" \-filte…

PostgreSQL技术内幕29:事件触发器tag原理解析

文章目录 0.简介1.概念说明2.tag的生成和存储2.1 tag合法性校验2.2 内存中存储2.3 持久化存储 3.tag的触发 0.简介 在上一篇文章中中&#xff0c;我们介绍了PG中的两种触发器&#xff0c;即适合于DML的普通触发器和对于DDL的事件触发器&#xff0c;其中事件触发器与常规的 DML…

mysql 导入很慢,如何解决

精选 原创 码出财富2025-04-14 17:35:14博主文章分类&#xff1a;数据库©著作权 文章标签mysql数据库用户名文章分类MySQL数据库yyds干货盘点阅读数184 导入大型 SQL 文件到 MySQL 数据库时&#xff0c;速度可能会受到影响。以下是一些优化方法和建议&#xff0c;帮助你…

多物理场耦合低温等离子体装置求解器PASSKEy2

文章目录 PASSKEy2简介PASSKEY2计算流程PASSKEy2 中求解的物理方程电路模型等离子体模型燃烧模型 PASSKEy2的使用 PASSKEy2简介 PASSKEy2 是在 PASSKEy1 的基础上重新编写的等离子体数值模拟程序。 相较于 PASSKEy1&#xff0c; PASSKEy2 在具备解决低温等离子体模拟问题的能力…

保姆级zabbix监控jmx、数据库和网络监控(SNMP)

前言 在当今数字化时代&#xff0c;企业IT基础设施的稳定性与性能直接关系到业务连续性和用户体验。随着系统复杂性的不断增加&#xff0c;单一维度的监控已难以满足全面运维需求。Zabbix作为一款功能强大的开源监控解决方案&#xff0c;通过整合JMX&#xff08;Java Manageme…

复杂地形越野机器人导航新突破!VERTIFORMER:数据高效多任务Transformer助力越野机器人移动导航

作者&#xff1a; Mohammad Nazeri 1 ^{1} 1, Anuj Pokhrel 1 ^{1} 1, Alexandyr Card 1 ^{1} 1, Aniket Datar 1 ^{1} 1, Garrett Warnell 2 , 3 ^{2,3} 2,3, Xuesu Xiao 1 ^{1} 1单位&#xff1a; 1 ^{1} 1乔治梅森大学计算机科学系&#xff0c; 2 ^{2} 2美国陆军研究实验室&…

SharpMap与TerraLib:C#与C++开源GIS库

大家好&#xff0c;今天为大家介绍的软件是SharpMap&#xff1a;一款专为了C#&#xff08;.NET&#xff09;环境设计的开源地图和空间数据处理库&#xff1b;TerraLib&#xff1a;一款由C编写、支持多种数据库的开源的GIS软件库。 下面&#xff0c;我们将从两个开源软件的主要…

音视频学习 - MP3格式

环境 JDK 13 IDEA Build #IC-243.26053.27, built on March 16, 2025 Demo MP3Parser MP3 MP3全称为MPEG Audio Layer 3&#xff0c;它是一种高效的计算机音频编码方案&#xff0c;它以较大的压缩比将音频文件转换成较小的扩展名为.mp3的文件&#xff0c;基本保持源文件的音…

Unity中数据和资源加密(异或加密,AES加密,MD5加密)

在项目开发中&#xff0c;始终会涉及到的一个问题&#xff0c;就是信息安全&#xff0c;在调用接口&#xff0c;或者加载的资源&#xff0c;都会涉及安全问题&#xff0c;因此就出现了各种各样的加密方式。 常见的也是目前用的最广的加密方式&#xff0c;分别是&#xff1a;DE…

部署本地deepseek并在调用的详细步骤以及解决一些可能出现的问题(Windows,Linux, WSL)

打开Ollama官网&#xff1a;https://ollama.com/ 直接下载Ollama并且安装好Ollama、这时候就能看到app里多了个ollama&#xff0c;但是我们不用打开它 打开Windows Powershell&#xff1a; ollama run deepseek-r1:1.5b 7b 8b 14b 32b 70b 根据自己的电脑配置和需求更换不同的…

【KWDB 创作者计划】_嵌入式硬件篇---寄存器与存储器截断与溢出

文章目录 前言一、寄存器与存储器1. 定义与基本概念寄存器(Register)位置功能特点存储器(Memory)位置功能特点2. 关键区别3. 层级关系与协作存储层次结构协作示例4. 为什么需要寄存器性能优化指令支持减少总线竞争5. 其他寄存器类型专用寄存器程序计数器(PC)栈指针(SP)…

小白自学python第二天

学习python的第二天 一、判断语句 1、布尔类型和比较运算符 1、布尔类型 表示现实生活中的逻辑&#xff0c;真&#xff08;True&#xff0c;用数字1表示&#xff09;和假&#xff08;False&#xff0c;用数字0表示&#xff09; 2、布尔类型变量的定义 变量的名称 布尔类…

linux基础操作1------(文件命令)

一.前言 我们本章开始讲解linux&#xff0c;我们对于linux得有重要的认识&#xff0c;比如项目部署等等&#xff0c;都会用到linux&#xff0c;今天我们就开始linux的学习&#xff0c;我们需要准备的工具有vmware和xshell&#xff0c;而这里我就不教大家虚拟机的安装以及xshel…

编码问题整合

一、windows系统编码 查看编码命令&#xff1a;chcp - 936 GBK - 65001 UTF-8 - 437 英文修改系统编码 1、控制面板修改 需管理员权限-Windows 10/11进入 控制面板 > 区域 > 管理 > 更改系统区域设置勾选 Beta版: 使用Unicode UTF-8提供全球语言支持 → 重启生效修…

如何配置Spark

1.上传spark安装包到某一台机器&#xff08;自己在finaShell上的机器&#xff09;。 2.解压。 把第一步上传的安装包解压到/opt/module下&#xff08;也可以自己决定解压到哪里&#xff09;。对应的命令是&#xff1a;tar -zxvf 安装包 -C /opt/module 3.重命名。进入/opt/mo…

Redis 完整配置模板

一、基础连接配置&#xff08;单机模式&#xff09; 基础参数&#xff08;适用Spring Boot&#xff09; spring:redis:host: 127.0.0.1port: 6379password: your_passworddatabase: 0 # 默认DB索引timeout: 2000ms # 全局操作超时时间二、连接池参数&#xff08;通用核心配…

边界凸台建模与实例

文章目录 边界凸台特征耳机案例瓶子 边界凸台特征 两侧对称拉伸最上面的圆柱 同过两点一基准面画草图&#xff0c;在基准面上画椭圆 隐藏无关的实体和草图&#xff0c;以便椭圆的端点能与线给穿透约束&#xff0c;下面的点与下面的线也给穿透&#xff0c;短轴长给35&#xff08…

河北省大数据应用创新大赛样题

** 河北省大数据应用创新大赛样题 ** 1. 在Linux下安装Java并搭建完全分布式Hadoop集群。在Linux终端执行命令“initnetwork”&#xff0c;或双击桌面上名称为“初始化网络”的图标&#xff0c;初始化实训平台网络。 【数据获取】 使用wget命令获取JDK安装包&#xff1a; “w…