Spring Boot中RedisTemplate的使用

news/2024/5/6 3:31:45/文章来源:https://blog.csdn.net/y_bccl27/article/details/133987340

当前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());}
}

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

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

相关文章

【力扣刷题】只出现一次的数字、多数元素、环形链表 II、两数相加

&#x1f40c;个人主页&#xff1a; &#x1f40c; 叶落闲庭 &#x1f4a8;我的专栏&#xff1a;&#x1f4a8; c语言 数据结构 javaEE 操作系统 Redis 石可破也&#xff0c;而不可夺坚&#xff1b;丹可磨也&#xff0c;而不可夺赤。 刷题篇 一、只出现一次的数字1.1 题目描述1…

【Linux系统编程】命令模式2

目录 一&#xff0c;Linux下的初阶认识 1&#xff0c;管道 2&#xff0c;时间戳 二&#xff0c;Liunx系统命令操作 1&#xff0c;date时间指令 2&#xff0c;cal日历指令 3&#xff0c;which和find查找指令 3-1&#xff0c;which指令&#xff1a; 3-2&#xff0c;find…

分享一个python无人超市管理系统django项目实战源码调试 lw 开题

&#x1f495;&#x1f495;作者&#xff1a;计算机源码社 &#x1f495;&#x1f495;个人简介&#xff1a;本人七年开发经验&#xff0c;擅长Java、Python、PHP、.NET、微信小程序、爬虫、大数据等&#xff0c;大家有这一块的问题可以一起交流&#xff01; &#x1f495;&…

[Linux 基础] make、Makefile自动化构建代码工具

文章目录 1、make与Makefile是什么2、为什么要有make与Makefile3、怎么实现一个Makefile文件3.1 如何编写Makefile文件3.1.1 依赖关系3.1.2 依赖方法 3.2 如何清理项目3.2.1 如何编写3.2.2 clean详解 3.3 make的使用3.4 原理3.4.1 查看文件修改时间 1、make与Makefile是什么 m…

【王道代码】【2.3链表】d3

关键字&#xff1a; 奇偶序号拆分、a1&#xff0c;b1&#xff0c;a2&#xff0c;b2...an&#xff0c;bn拆分a1&#xff0c;a2...&#xff0c;bn&#xff0c;...b2&#xff0c;b1、删除相同元素

比例运算放大电路为什么要加平衡电阻

这个是反相比例运算放大电路&#xff0c;输出电压等于-Rf/R1乘以输入电压。 这个是同相比例运算放大电路&#xff0c;输出电压等于1Rf/R1乘以输入电压。 大家可以看到这两个电路中&#xff0c;都有一个电阻R2&#xff0c;反相比例运算放大电路放在同相端到地&#xff0c;同相比…

二叉排序树(BST)

二叉排序树 基本介绍 二叉排序树创建和遍历 class Node:"""创建 Node 节点"""value: int 0left Noneright Nonedef __init__(self, value: int):self.value valuedef add(self, node):"""添加节点node 表示要添加的节点&quo…

【C++】继承 ⑧ ( 继承 + 组合 模式的类对象 构造函数 和 析构函数 调用规则 )

文章目录 一、继承 组合 模式的类对象 构造函数和析构函数调用规则1、场景说明2、调用规则 二、完整代码示例分析1、代码分析2、代码示例 一、继承 组合 模式的类对象 构造函数和析构函数调用规则 1、场景说明 如果一个类 既 继承了 基类 ,又 在类中 维护了一个 其它类型 的…

找不到conda可执行文件:解决方法

1.在新版本的pycharm出现的问题如下&#xff1a; 2.解决方法: 2.1 将anaconda\Scripts\conda.exe选中 2.2选择自己的anconda自己的环境&#xff0c;之后就可以正常创建conda环境

2023-10-23 LeetCode每日一题(老人的数目)

2023-10-23每日一题 一、题目编号 2678. 老人的数目二、题目链接 点击跳转到题目位置 三、题目描述 给你一个下标从 0 开始的字符串 details 。details 中每个元素都是一位乘客的信息&#xff0c;信息用长度为 15 的字符串表示&#xff0c;表示方式如下&#xff1a; 前十…

橙河网络:国外问卷调查赚钱的项目可靠吗?

国外问卷调查项目是可靠的&#xff0c;是一个长期稳定的互联网项目。 大家好&#xff0c;我是橙河网络&#xff0c;今天聊一聊国外问卷调查赚钱的项目可靠吗&#xff1f; 在海外地区&#xff0c;很多公司和机构&#xff0c;它们为了收集一些关于产品和服务的消费者意见&#…

深入浅出Apache SeaTunnel SQL Server Sink Connector

在大数据时代&#xff0c;数据的迁移和流动已经变得日益重要。为了使数据能够更加高效地从一个源流向另一个目标&#xff0c;我们需要可靠、高效和易于配置的工具。今天&#xff0c;我们将介绍 JDBC SQL Server Sink Connector&#xff0c;这是一个专为 SQL Server 设计的连接器…

MyBatis-Plus实现逻辑删除[MyBatis-Plus系列] - 492篇

历史文章&#xff08;文章累计490&#xff09; 《国内最全的Spring Boot系列之一》 《国内最全的Spring Boot系列之二》 《国内最全的Spring Boot系列之三》 《国内最全的Spring Boot系列之四》 《国内最全的Spring Boot系列之五》 《国内最全的Spring Boot系列之六》 M…

【鸿蒙软件开发】文本输入(TextInput/TextArea)

文章目录 前言一、输入框1.1 创建输入框单行输入框多行输入框单行和多行输入框的区别 1.2 设置输入框的类型有哪些类型基本输入模式&#xff08;默认类型&#xff09;密码输入模式 1.3 自定义样式设置无输入时的提示文本设置输入框当前的文本内容。添加backgroundColor改变输入…

MECE分析法

1、前言 前段时间在对项目进行问题分析的时候&#xff0c;领导要求要符合MECE原则&#xff0c;做到逻辑完整而不能遗漏。虽然没听过这个原则&#xff0c;但是总感觉很有道理&#xff08;领导说的都对&#xff09;。于是乎&#xff0c;就找了一些资料了解了一下。 MECE分析法是…

【Rust】4 一文讲解重点 pattern matching | trait | 生命周期 | 闭包 | 迭代器 | 智能指针 | 并发与并行

文章目录 一、pattern matching二、trait2.1 常见 trait2.1.1 Copy 和 Clone2.1.2 PartialEq 和 Eq2.1.3 PartialOrd 和 Ord2.1.4 Hash2.1.5 From, Into, TryFrom, TryInto 2.2 概念2.2.1 关联类型2.2.2 关联常量2.3.3 泛型关联类型2.3.3.1 示例: 用泛型关联类型, 创建集合工厂…

快手进与退,快手董事长在辞任前套现37.78亿港元

快手科技&#xff08;1024.HK&#xff09;在港交所发布公告&#xff0c;宣布自2023年10月29日起&#xff0c;公司创始人宿华将不再担任董事会董事长&#xff0c;而继续担任执行董事和薪酬委员会成员&#xff0c;而他的不同投票权将保持不变。与此同时&#xff0c;快手科技的现任…

爱创科技携手洽洽食品,探索渠道数字化最优解!

坚果的下半场&#xff0c;是从吃到喝。 消费升级大潮下&#xff0c;健康养生理念逐渐深入人心。以“天然健康”为核心的食品新消费潮流正加速形成&#xff0c;一个个打着“美味与营养”黄金设定的品类风口正被不断创建&#xff0c;其中人气有增无减的当属植物基饮品。据相关报告…

【蓝桥杯001】

个人名片&#xff1a; &#x1f43c;作者简介&#xff1a;一名大二在校生&#xff0c;喜欢编程&#x1f38b; &#x1f43b;‍❄️个人主页&#x1f947;&#xff1a;小新爱学习. &#x1f43c;个人WeChat&#xff1a;hmmwx53 &#x1f54a;️系列专栏&#xff1a;&#x1f5bc…

pv操作题目笔记

对于 pv 操作分以下几步走 什么是pv操作 PV操作在进程同步中通常指的是信号量&#xff08;Semaphore&#xff09;操作。信号量是一种用于控制多个并发进程或线程之间的同步和互斥访问的同步工具。PV操作通常涉及两个基本操作&#xff1a;P操作&#xff08;wait操作&#xff0…