当前位置: 首页 > 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;才能成功登…...

conda相比python好处

Conda 作为 Python 的环境和包管理工具&#xff0c;相比原生 Python 生态&#xff08;如 pip 虚拟环境&#xff09;有许多独特优势&#xff0c;尤其在多项目管理、依赖处理和跨平台兼容性等方面表现更优。以下是 Conda 的核心好处&#xff1a; 一、一站式环境管理&#xff1a…...

黑马Mybatis

Mybatis 表现层&#xff1a;页面展示 业务层&#xff1a;逻辑处理 持久层&#xff1a;持久数据化保存 在这里插入图片描述 Mybatis快速入门 ![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/6501c2109c4442118ceb6014725e48e4.png //logback.xml <?xml ver…...

Spring Boot+Neo4j知识图谱实战:3步搭建智能关系网络!

一、引言 在数据驱动的背景下&#xff0c;知识图谱凭借其高效的信息组织能力&#xff0c;正逐步成为各行业应用的关键技术。本文聚焦 Spring Boot与Neo4j图数据库的技术结合&#xff0c;探讨知识图谱开发的实现细节&#xff0c;帮助读者掌握该技术栈在实际项目中的落地方法。 …...

【C++从零实现Json-Rpc框架】第六弹 —— 服务端模块划分

一、项目背景回顾 前五弹完成了Json-Rpc协议解析、请求处理、客户端调用等基础模块搭建。 本弹重点聚焦于服务端的模块划分与架构设计&#xff0c;提升代码结构的可维护性与扩展性。 二、服务端模块设计目标 高内聚低耦合&#xff1a;各模块职责清晰&#xff0c;便于独立开发…...

Redis数据倾斜问题解决

Redis 数据倾斜问题解析与解决方案 什么是 Redis 数据倾斜 Redis 数据倾斜指的是在 Redis 集群中&#xff0c;部分节点存储的数据量或访问量远高于其他节点&#xff0c;导致这些节点负载过高&#xff0c;影响整体性能。 数据倾斜的主要表现 部分节点内存使用率远高于其他节…...

精益数据分析(97/126):邮件营销与用户参与度的关键指标优化指南

精益数据分析&#xff08;97/126&#xff09;&#xff1a;邮件营销与用户参与度的关键指标优化指南 在数字化营销时代&#xff0c;邮件列表效度、用户参与度和网站性能等指标往往决定着创业公司的增长成败。今天&#xff0c;我们将深入解析邮件打开率、网站可用性、页面参与时…...

大语言模型(LLM)中的KV缓存压缩与动态稀疏注意力机制设计

随着大语言模型&#xff08;LLM&#xff09;参数规模的增长&#xff0c;推理阶段的内存占用和计算复杂度成为核心挑战。传统注意力机制的计算复杂度随序列长度呈二次方增长&#xff0c;而KV缓存的内存消耗可能高达数十GB&#xff08;例如Llama2-7B处理100K token时需50GB内存&a…...

【生成模型】视频生成论文调研

工作清单 上游应用方向&#xff1a;控制、速度、时长、高动态、多主体驱动 类型工作基础模型WAN / WAN-VACE / HunyuanVideo控制条件轨迹控制ATI~镜头控制ReCamMaster~多主体驱动Phantom~音频驱动Let Them Talk: Audio-Driven Multi-Person Conversational Video Generation速…...

毫米波雷达基础理论(3D+4D)

3D、4D毫米波雷达基础知识及厂商选型 PreView : https://mp.weixin.qq.com/s/bQkju4r6med7I3TBGJI_bQ 1. FMCW毫米波雷达基础知识 主要参考博文&#xff1a; 一文入门汽车毫米波雷达基本原理 &#xff1a;https://mp.weixin.qq.com/s/_EN7A5lKcz2Eh8dLnjE19w 毫米波雷达基础…...

【p2p、分布式,区块链笔记 MESH】Bluetooth蓝牙通信 BLE Mesh协议的拓扑结构 定向转发机制

目录 节点的功能承载层&#xff08;GATT/Adv&#xff09;局限性&#xff1a; 拓扑关系定向转发机制定向转发意义 CG 节点的功能 节点的功能由节点支持的特性和功能决定。所有节点都能够发送和接收网格消息。节点还可以选择支持一个或多个附加功能&#xff0c;如 Configuration …...