当前位置: 首页 > 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);}
}
http://www.lryc.cn/news/205813.html

相关文章:

  • GSCoolink GSV6183 带嵌入式MCU的MIPI D-PHY 转 DP/eDP
  • Linux文件系统 struct dentry 结构体解析
  • C++——vector
  • html5语义化标签
  • SQL Server批量删除数据库中的表
  • 使用SecScanC2构建P2P去中心化网络实现反溯源
  • 【API篇】七、Flink窗口
  • 软件测试面试1000问(含文档)
  • 进阶课4——随机森林
  • 【Docker】Dockerfile使用技巧
  • 一招解决“请在微信客户端中打开链接”
  • Python循环语句(一)
  • 期中考核复现
  • 基于XML的Web服务Java接口(JAX-WS)、Jakarta XML Web Services Eclipse 实现
  • 公网无信号区域远程抄表问题解决方案及产品选型
  • lunar-1.5.jar
  • c++编译使用log4cplus
  • zookeeper源码(02)源码编译启动及idea导入
  • Github 2FA绑定中国+86手机号码实现两步验证
  • windows安装mysql-8.0.35
  • 最详细STM32,cubeMX串口发送,接收数据
  • Kafka入门04——原理分析
  • k8s-----17、集群安全机制
  • 蓝桥算法赛(铺地板)
  • 浅谈AcrelEMS-GYM文体建筑能效管理解决方案-安科瑞 蒋静
  • 在LayerUI中使用onChange事件监听复选框的值变化
  • 决策树--ID3算法
  • js延时加载有哪些方式
  • VSCode运行python提示No module name ‘xxx‘
  • 【网安大模型专题10.19】※论文5:ChatGPT+漏洞定位+补丁生成+补丁验证+APR方法+ChatRepair+不同修复场景+修复效果(韦恩图展示)