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

Spring Boot中RedisTemplate的使用

当前Spring Boot的版本为2.7.6,在使用RedisTemplate之前我们需要在pom.xml中引入下述依赖:

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

同时在application.yml文件中添加下述配置:

springredis:host: 127.0.0.1port: 6379

一、opsForHash 

RedisTemplate.opsForHash()是RedisTemplate类提供的用于操作Hash类型的方法,它可以用于对Redis中的Hash数据结构进行各种操作,如设置字段值、获取字段值、删除字段值等。

1.1 设置哈希字段的值

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;@SpringBootTest
public class DemoApplicationTests {@Autowiredprivate RedisTemplate redisTemplate;@Testvoid test(){redisTemplate.opsForHash().put("fruit:list", "1", "苹果");}
}

在上述代码能正常运行的情况下,我们在终端中执行 redis-cli 命令进入到redis的控制台中,然后执行 keys * 命令查看所有的key,结果发现存储在redis中的key不是设置的string值,前面还多出了许多类似 \xac\xed\x00\x05t\x00 这种字符串,如下图所示:

这是因为Spring-Data-Redis的RedisTemplate<K, V>模板类在操作redis时默认使用JdkSerializationRedisSerializer来进行序列化,因此我们要更改其序列化方式:

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.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;@Configuration
public class RedisTemplateConfig {@Beanpublic RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {RedisTemplate<Object,Object> redisTemplate = new RedisTemplate<>();redisTemplate.setConnectionFactory(redisConnectionFactory);RedisSerializer stringRedisSerializer = new StringRedisSerializer();redisTemplate.setKeySerializer(stringRedisSerializer);redisTemplate.setValueSerializer(stringRedisSerializer);redisTemplate.setHashKeySerializer(stringRedisSerializer);redisTemplate.setHashValueSerializer(stringRedisSerializer);return redisTemplate;}
}

需要说明的是这种配置只是针对所有的数据都是String类型,如果是其它类型,则根据需求修改一下序列化方式。 

使用 flushdb 命令清除完所有的数据以后,再次执行上述测试案例,接着我们再次去查看所有的key,这个看到数据已经正常:

接着使用 hget fruit:list 1 命令去查询刚刚存储的数据,这时又发现对应字段的值中文显示乱码:

\xe8\x8b\xb9\xe6\x9e\x9c

这个时候需要我们在进入redis控制台前,添加 --raw 参数:

redis-cli --raw

1.2 设置多个哈希字段的值

设置多个哈希字段的值一种很简单的粗暴的方法是多次执行opsForHash().put()方法,另外一种更优雅的方式如下:

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 java.util.HashMap;
import java.util.Map;@SpringBootTest
public class DemoApplicationTests {@Autowiredprivate RedisTemplate redisTemplate;@Testvoid test(){Map<String,String> map = new HashMap<>();map.put("1","苹果");map.put("2","橘子");map.put("3","香蕉");redisTemplate.opsForHash().putAll("fruit:list",map);}
}

1.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;@SpringBootTest
public class DemoApplicationTests {@Autowiredprivate RedisTemplate redisTemplate;@Testvoid test(){String value = (String) redisTemplate.opsForHash().get("fruit:list","1");System.out.println(value);}
}

1.4 获取多个哈希字段的值

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 java.util.Arrays;
import java.util.List;@SpringBootTest
public class DemoApplicationTests {@Autowiredprivate RedisTemplate redisTemplate;@Testvoid test(){List<String> values = redisTemplate.opsForHash().multiGet("fruit:list", Arrays.asList("1", "2","3"));System.out.println(values);}
}

1.5 判断哈希中是否存在指定的字段

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;@SpringBootTest
public class DemoApplicationTests {@Autowiredprivate RedisTemplate redisTemplate;@Testvoid test(){Boolean hasKey = redisTemplate.opsForHash().hasKey("fruit:list", "1");System.out.println(hasKey);}
}

1.6 获取哈希的所有字段

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 java.util.Set;@SpringBootTest
public class DemoApplicationTests {@Autowiredprivate RedisTemplate redisTemplate;@Testvoid test(){Set<String> keys = redisTemplate.opsForHash().keys("fruit:list");System.out.println(keys);}
}

1.7 获取哈希的所有字段的值

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 java.util.List;@SpringBootTest
public class DemoApplicationTests {@Autowiredprivate RedisTemplate redisTemplate;@Testvoid test(){List<String> values = redisTemplate.opsForHash().values("fruit:list");System.out.println(values);}
}

1.8 获取哈希的所有字段和对应的值

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 java.util.Map;@SpringBootTest
public class DemoApplicationTests {@Autowiredprivate RedisTemplate redisTemplate;@Testvoid test(){Map<String, String> entries = redisTemplate.opsForHash().entries("fruit:list");System.out.println(entries);}
}

1.9 删除指定的字段 

返回值返回的是删除成功的字段的数量,如果字段不存在的话,则返回的是0。 

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;@SpringBootTest
public class DemoApplicationTests {@Autowiredprivate RedisTemplate redisTemplate;@Testvoid test(){Long deletedFields = redisTemplate.opsForHash().delete("fruit:list", "4");System.out.println(deletedFields);}
}

1.10 如果哈希的字段存在则不会添加,不存在则添加 

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;@SpringBootTest
public class DemoApplicationTests {@Autowiredprivate RedisTemplate redisTemplate;@Testvoid test(){Boolean success =  redisTemplate.opsForHash().putIfAbsent("fruit:list","4","西瓜");System.out.println(success);}
}

1.11 将指定字段的值增加指定步长

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;@SpringBootTest
public class DemoApplicationTests {@Autowiredprivate RedisTemplate redisTemplate;@Testvoid test(){Long incrementedValue = redisTemplate.opsForHash().increment("salary:list", "1", 5);System.out.println(incrementedValue);}
}

如果字段不存在,则将该字段的值设置为指定步长,并且返回该字段当前的值;如果字段存在,则在该字段原有值的基础上增加指定步长,返回该字段当前的最新值。 该方法只适用于字段值为int类型的数据,因此关于哈希数据结构的value值的序列化方式要有所改变

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.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;@Configuration
public class RedisTemplateConfig {@Beanpublic RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {RedisTemplate<Object,Object> redisTemplate = new RedisTemplate<>();redisTemplate.setConnectionFactory(redisConnectionFactory);RedisSerializer stringRedisSerializer = new StringRedisSerializer();redisTemplate.setKeySerializer(stringRedisSerializer);redisTemplate.setValueSerializer(stringRedisSerializer);redisTemplate.setHashKeySerializer(stringRedisSerializer);Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);return redisTemplate;}
}

StringRedisTemplate的好处就是在RedisTemplate基础上封装了一层,指定了所有数据的序列化方式都是采用StringRedisSerializer(即字符串),使用语法上面完全一致。 

public class StringRedisTemplate extends RedisTemplate<String, String> {public StringRedisTemplate() {this.setKeySerializer(RedisSerializer.string());this.setValueSerializer(RedisSerializer.string());this.setHashKeySerializer(RedisSerializer.string());this.setHashValueSerializer(RedisSerializer.string());}
}

二、opsForValue

RedisTemplate.opsForValue()是RedisTemplate类提供的用于操作字符串值类型的方法。它可以用于对Redis中的字符串值进行各种操作,如设置值、获取值、删除值等。

2.1 设置一个键值对

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 java.util.concurrent.TimeUnit;@SpringBootTest
public class DemoApplicationTests {@Autowiredprivate RedisTemplate redisTemplate;@Testvoid test(){String key = "fruit";String value = "apple";redisTemplate.opsForValue().set(key,value,30,TimeUnit.SECONDS);}
}

2.2 根据键获取对应的值 

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;@SpringBootTest
public class DemoApplicationTests {@Autowiredprivate RedisTemplate redisTemplate;@Testvoid test(){String value = (String) redisTemplate.opsForValue().get("fruit");System.out.println(value);}
}

相关文章:

Spring Boot中RedisTemplate的使用

当前Spring Boot的版本为2.7.6&#xff0c;在使用RedisTemplate之前我们需要在pom.xml中引入下述依赖&#xff1a; <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId><vers…...

GSCoolink GSV6183 带嵌入式MCU的MIPI D-PHY 转 DP/eDP

Gscoolink GSV6183是一款高性能、低功耗的MIPI D-PHY到DisplayPort/eDP 1.4转换器。通过集成基于RISC-V的增强型微控制器&#xff0c;GSV6183创造了一种具有成本效益的解决方案&#xff0c;提供了上市时间优势。MIPI D-PHY接收器支持CSI-2版本1.3和DSI版本1.3&#xff0c;每条通…...

Linux文件系统 struct dentry 结构体解析

文章目录 前言一、目录项简介二、struct dentry2.1 简介2.2 dentry和inode关联2.3 目录项视图2.4 目录项状态2.5 目录项特点 三、dentry cache3.1 简介3.2 dentry cache 初始化3.3 dentry cache 查看 四、dentry与mount、file的关联五、其他参考资料 前言 这两篇文章介绍了: V…...

C++——vector

目录 vector vector常用接口 构造函数 operator[]size() 迭代器 范围for capacity() resize() reverse() push_back和pop_back insert erase() algorithm::sort 注意 迭代器失效 vector vector单词直译是向量的意思&#xff0c;这个容器可以容纳不同的类型数据&am…...

html5语义化标签

目录 前言 什么是语义化标签 常见的语义化标签 语义化的好处 前言 HTML5 的设计目的是为了在移动设备上支持多媒体。之前网页如果想嵌入视频音频&#xff0c;需要用到 flash &#xff0c;但是苹果设备是不支持 flash 的&#xff0c;所以为了改变这一现状&#xff0c;html5 …...

SQL Server批量删除数据库中的表

如果想要删除数据库中temp 开头的中间表 1. SQL 语句实现 use [DBName] --todo go select drop table name from sys.tables where name like temp% go 将查询结果粘贴到数据库中运行 2. 数据库 单击目标数据库中的Tables ,然后按F7 键&#xff0c;按Name 进行排序&…...

使用SecScanC2构建P2P去中心化网络实现反溯源

个人博客: xzajyjs.cn 前言 这款工具是为了帮助安全研究人员在渗透测试过程中防止扫描被封禁、保护自己免溯源的一种新思路。其利用到了区块链中的p2p点对点去中心化技术构建以来构建代理池。 工具链接&#xff1a;https://github.com/xzajyjs/SecScanC2 实验过程 该工具分为…...

【API篇】七、Flink窗口

文章目录 1、窗口2、分类3、窗口API概览4、窗口分配器 在批处理统计中&#xff0c;可以等待一批数据都到齐后&#xff0c;统一处理。但是在无界流的实时处理统计中&#xff0c;是来一条就得处理一条&#xff0c;那么如何统计最近一段时间内的数据呢&#xff1f; ⇒ 窗口的概念&…...

软件测试面试1000问(含文档)

前前后后面试了有20多家的公司吧&#xff0c;最近抽空把当时的录音整理了下&#xff0c;然后给大家分享下 开头都是差不多&#xff0c;就让做一个自我介绍&#xff0c;这个不用再给大家普及了吧 同时&#xff0c;我也准备了一份软件测试视频教程&#xff08;含接口、自动化、…...

进阶课4——随机森林

1.定义 随机森林是一种集成学习方法&#xff0c;它利用多棵树对样本进行训练并预测。 随机森林指的是利用多棵树对样本进行训练并预测的一种分类器&#xff0c;每棵树都由随机选择的一部分特征进行训练和构建。通过多棵树的集成&#xff0c;可以增加模型的多样性和泛化能力。…...

【Docker】Dockerfile使用技巧

开启Buildkit BuildKit是Docker官方社区推出的下一代镜像构建神器&#xff0c;可以更加快速&#xff0c;有效&#xff0c;安全地构建docker镜像。 尽管目前BuildKit不是Docker的默认构建工具&#xff0c;但是完全可以考虑将其作为Docker&#xff08;v18.09&#xff09;的首选…...

一招解决“请在微信客户端中打开链接”

一招解决“请在微信客户端中打开链接”-遇见你与你分享 在浏览器访问网站&#xff0c;却提示“请在微信客户端打开链接”。虽然这个情况你可能从未遇到过&#xff0c;但对于爱折腾的小伙伴&#xff0c;确是一道拦路虎 其实解决办法很简单&#xff0c;就是新建一个UA&#xff1…...

Python循环语句(一)

目录 一.while循环1.while循环的基础语法2.while循环的嵌套应用3.while循环嵌套案例 一.while循环 1.while循环的基础语法 while循环注意点 while的条件需得到布尔类型&#xff0c;True表示继续循环&#xff0c;False表示结束循环需要设置循环终止的条件&#xff0c;如i 1配…...

期中考核复现

web 1z_php ?0o0[]1A&OoO[]2023a include "flag.php"&#xff1a;尝试包含名为 "flag.php" 的文件。这意味着它会尝试引入一个名为 "flag.php" 的脚本文件&#xff0c;其中可能包含一些敏感信息或标志。 error_reporting(0)&#xff1a;…...

基于XML的Web服务Java接口(JAX-WS)、Jakarta XML Web Services Eclipse 实现

简介 JAX-WS&#xff08;Java API for XML-Based Web Services&#xff09;&#xff0c;是创建web服务的Java编程接口&#xff0c;特别是SOAP服务。是Java XML编程接口之一&#xff0c;是Java SE 和Java EE 平台的一部分。 JAX-WS 2.0 规范是代替JAX-RPC 1.0的下一代Web服务AP…...

公网无信号区域远程抄表问题解决方案及产品选型

摘要&#xff1a;随着计量自动化系统的逐步完善&#xff0c;电网全用户表码信息采集成为系统数据得以深化应用的重要基础。利用无线公网通信是目前实现远程抄表的主要手段之一&#xff0c;但仍存在公网难以覆盖的偏远山区、公网信号屏蔽地下室或弱信号区域&#xff0c;无法实现…...

lunar-1.5.jar

公历农历转换包 https://mvnrepository.com/artifact/com.github.heqiao2010/lunar <!-- https://mvnrepository.com/artifact/com.github.heqiao2010/lunar --> <dependency> <groupId>com.github.heqiao2010</groupId> <artifactId>l…...

c++编译使用log4cplus

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 前言一、log4cplus是什么&#xff1f;二、使用步骤1.下载源代码2.开始配置1.配置介绍2.开始编译 3.cmake引用4.示例 总结 前言 C很强大&#xff0c;但是仍然有很多…...

zookeeper源码(02)源码编译启动及idea导入

本文介绍一下zookeeper-3.9.0源码下载、编译及本地启动。 下载源码 git clone https://gitee.com/apache/zookeeper.gitcd zookeeper git checkout release-3.9.0 git checkout -b release-3.9.0源码编译 README_packaging.md文件 该文件介绍了编译zookeeper需要的环境和命…...

Github 2FA绑定中国+86手机号码实现两步验证

GitHub宣布&#xff0c;到 2023 年底&#xff0c;所有用户都必须要启用双因素身份验证 (2FA)&#xff0c;不能只用密码. GitHub开启2FA后&#xff0c;除了输入密码外&#xff0c;还需要通过一次性密码&#xff08;OTP&#xff09;等方式做第二级身份验证&#xff0c;才能成功登…...

MySQL 隔离级别:脏读、幻读及不可重复读的原理与示例

一、MySQL 隔离级别 MySQL 提供了四种隔离级别,用于控制事务之间的并发访问以及数据的可见性,不同隔离级别对脏读、幻读、不可重复读这几种并发数据问题有着不同的处理方式,具体如下: 隔离级别脏读不可重复读幻读性能特点及锁机制读未提交(READ UNCOMMITTED)允许出现允许…...

基于uniapp+WebSocket实现聊天对话、消息监听、消息推送、聊天室等功能,多端兼容

基于 ​UniApp + WebSocket​实现多端兼容的实时通讯系统,涵盖WebSocket连接建立、消息收发机制、多端兼容性配置、消息实时监听等功能,适配​微信小程序、H5、Android、iOS等终端 目录 技术选型分析WebSocket协议优势UniApp跨平台特性WebSocket 基础实现连接管理消息收发连接…...

STM32+rt-thread判断是否联网

一、根据NETDEV_FLAG_INTERNET_UP位判断 static bool is_conncected(void) {struct netdev *dev RT_NULL;dev netdev_get_first_by_flags(NETDEV_FLAG_INTERNET_UP);if (dev RT_NULL){printf("wait netdev internet up...");return false;}else{printf("loc…...

新能源汽车智慧充电桩管理方案:新能源充电桩散热问题及消防安全监管方案

随着新能源汽车的快速普及&#xff0c;充电桩作为核心配套设施&#xff0c;其安全性与可靠性备受关注。然而&#xff0c;在高温、高负荷运行环境下&#xff0c;充电桩的散热问题与消防安全隐患日益凸显&#xff0c;成为制约行业发展的关键瓶颈。 如何通过智慧化管理手段优化散…...

基于Docker Compose部署Java微服务项目

一. 创建根项目 根项目&#xff08;父项目&#xff09;主要用于依赖管理 一些需要注意的点&#xff1a; 打包方式需要为 pom<modules>里需要注册子模块不要引入maven的打包插件&#xff0c;否则打包时会出问题 <?xml version"1.0" encoding"UTF-8…...

(转)什么是DockerCompose?它有什么作用?

一、什么是DockerCompose? DockerCompose可以基于Compose文件帮我们快速的部署分布式应用&#xff0c;而无需手动一个个创建和运行容器。 Compose文件是一个文本文件&#xff0c;通过指令定义集群中的每个容器如何运行。 DockerCompose就是把DockerFile转换成指令去运行。 …...

根据万维钢·精英日课6的内容,使用AI(2025)可以参考以下方法:

根据万维钢精英日课6的内容&#xff0c;使用AI&#xff08;2025&#xff09;可以参考以下方法&#xff1a; 四个洞见 模型已经比人聪明&#xff1a;以ChatGPT o3为代表的AI非常强大&#xff0c;能运用高级理论解释道理、引用最新学术论文&#xff0c;生成对顶尖科学家都有用的…...

Java 二维码

Java 二维码 **技术&#xff1a;**谷歌 ZXing 实现 首先添加依赖 <!-- 二维码依赖 --><dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>3.5.1</version></dependency><de…...

深度学习水论文:mamba+图像增强

&#x1f9c0;当前视觉领域对高效长序列建模需求激增&#xff0c;对Mamba图像增强这方向的研究自然也逐渐火热。原因在于其高效长程建模&#xff0c;以及动态计算优势&#xff0c;在图像质量提升和细节恢复方面有难以替代的作用。 &#x1f9c0;因此短时间内&#xff0c;就有不…...

【JavaSE】多线程基础学习笔记

多线程基础 -线程相关概念 程序&#xff08;Program&#xff09; 是为完成特定任务、用某种语言编写的一组指令的集合简单的说:就是我们写的代码 进程 进程是指运行中的程序&#xff0c;比如我们使用QQ&#xff0c;就启动了一个进程&#xff0c;操作系统就会为该进程分配内存…...