在Spring Boot微服务使用ValueOperations操作Redis String字符串

news/2024/9/22 18:24:16/

记录:401

场景:在Spring Boot微服务使用RedisTemplate的ValueOperations操作Redis String字符串。

版本:JDK 1.8,Spring Boot 2.6.3,redis-6.2.5

1.微服务中Redis配置信息

1.1在application.yml中Redis配置信息

spring:redis:host: 192.168.19.203port: 28001password: 12345678timeout: 50000

1.2加载简要逻辑

Spring Boot微服务在启动时,自动注解机制会读取application.yml的注入到RedisProperties对象。在Spring环境中就能取到Redis相关配置信息了。

类全称:org.springframework.boot.autoconfigure.data.redis.RedisProperties

1.3在pom.xml添加依赖

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

2.配置RedisTemplate

2.1配置RedisTemplate

@Configuration
public class RedisConfig {@Bean("redisTemplate")public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {// 1.创建RedisTemplate对象RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();// 2.加载Redis配置redisTemplate.setConnectionFactory(lettuceConnectionFactory);// 3.配置key序列化RedisSerializer<?> stringRedisSerializer = new StringRedisSerializer();redisTemplate.setKeySerializer(stringRedisSerializer);redisTemplate.setHashKeySerializer(stringRedisSerializer);// 4.配置Value序列化Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);ObjectMapper objMapper = new ObjectMapper();objMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);objMapper.activateDefaultTyping(objMapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);jackson2JsonRedisSerializer.setObjectMapper(objMapper);redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);// 5.初始化RedisTemplateredisTemplate.afterPropertiesSet();return redisTemplate;}@Beanpublic ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {return redisTemplate.opsForValue();}
}

2.2解析

在配置RedisTemplate后,在Spring环境中,可以@Autowired自动注入方式注入操作Redis对象。比如:RedisTemplate、ValueOperations。

3.使用ValueOperations操作Redis String字符串

3.1简要说明

使用ValueOperations操作字符串,常用操作:增、查、改、删、设置超时等。

3.2操作示例

@RestController
@RequestMapping("/hub/example/load")
@Slf4j
public class LoadController {@Autowiredprivate RedisTemplate redisTemplate;@Autowiredprivate ValueOperations valueOperations;/*** 操作String,使用ValueOperations* 对应写命令: SET key value* 对应读命令: GET key*/@GetMapping("/valueOperations")public Object loadData02() {log.info("ValueOperations操作开始...");// 1.增valueOperations.set("CityInfo:Hangzhou02", "杭州");valueOperations.set("CityInfo:Hangzhou02", "苏州");// 2.查Object result01 = valueOperations.get("CityInfo:Hangzhou02");log.info("result01 = " + result01.toString());// 3.改valueOperations.set("CityInfo:Hangzhou02", "杭州-西湖");// 4.删String result02 = (String) valueOperations.getAndDelete("CityInfo:Hangzhou02");redisTemplate.delete("CityInfo:Hangzhou02");// 5.1设置超时(方式一)valueOperations.set("CityInfo:Hangzhou02", "杭州-西湖");valueOperations.getAndExpire("CityInfo:Hangzhou02", 5, TimeUnit.MINUTES);// 5.2设置超时(方式二)valueOperations.set("CityInfo:Hangzhou02", "杭州-西湖");redisTemplate.expire("CityInfo:Hangzhou02", 10, TimeUnit.MINUTES);// 6.查询Value的字节大小Long size =valueOperations.size("CityInfo:Hangzhou02");System.out.println("缓存字节大小,size="+size +" bytes");log.info("ValueOperations操作结束...");return "执行成功";}
}

3.3测试验证

使用Postman测试。

请求RUL:http://127.0.0.1:18205/hub-205-redis/hub/example/load/valueOperations

4.ValueOperations接口

4.1接口

ValueOperations是一个接口,默认实现类是DefaultValueOperations。

接口:org.springframework.data.redis.core.ValueOperations。

实现类:org.springframework.data.redis.core.DefaultValueOperations。

4.2接口源码

在源码中,查看接口具体方法,可以快速了解该接口具备功能,以便在生产中能根据实际场景对号入座找到合适方法解决实际问题。

public interface ValueOperations<K, V> {void set(K key, V value);void set(K key, V value, long timeout, TimeUnit unit);default void set(K key, V value, Duration timeout) {Assert.notNull(timeout, "Timeout must not be null!");if (TimeoutUtils.hasMillis(timeout)) {this.set(key, value, timeout.toMillis(), TimeUnit.MILLISECONDS);} else {this.set(key, value, timeout.getSeconds(), TimeUnit.SECONDS);}}@NullableBoolean setIfAbsent(K key, V value);@NullableBoolean setIfAbsent(K key, V value, long timeout, TimeUnit unit);@Nullabledefault Boolean setIfAbsent(K key, V value, Duration timeout) {Assert.notNull(timeout, "Timeout must not be null!");return TimeoutUtils.hasMillis(timeout) ? this.setIfAbsent(key, value, timeout.toMillis(), TimeUnit.MILLISECONDS) : this.setIfAbsent(key, value, timeout.getSeconds(), TimeUnit.SECONDS);}@NullableBoolean setIfPresent(K key, V value);@NullableBoolean setIfPresent(K key, V value, long timeout, TimeUnit unit);@Nullabledefault Boolean setIfPresent(K key, V value, Duration timeout) {Assert.notNull(timeout, "Timeout must not be null!");return TimeoutUtils.hasMillis(timeout) ? this.setIfPresent(key, value, timeout.toMillis(), TimeUnit.MILLISECONDS) : this.setIfPresent(key, value, timeout.getSeconds(), TimeUnit.SECONDS);}void multiSet(Map<? extends K, ? extends V> map);@NullableBoolean multiSetIfAbsent(Map<? extends K, ? extends V> map);@NullableV get(Object key);@NullableV getAndDelete(K key);@NullableV getAndExpire(K key, long timeout, TimeUnit unit);@NullableV getAndExpire(K key, Duration timeout);@NullableV getAndPersist(K key);@NullableV getAndSet(K key, V value);@NullableList<V> multiGet(Collection<K> keys);@NullableLong increment(K key);@NullableLong increment(K key, long delta);@NullableDouble increment(K key, double delta);@NullableLong decrement(K key);@NullableLong decrement(K key, long delta);@NullableInteger append(K key, String value);@NullableString get(K key, long start, long end);void set(K key, V value, long offset);@NullableLong size(K key);@NullableBoolean setBit(K key, long offset, boolean value);@NullableBoolean getBit(K key, long offset);@NullableList<Long> bitField(K key, BitFieldSubCommands subCommands);RedisOperations<K, V> getOperations();
}

以上,感谢。

2023年4月12日


http://www.ppmy.cn/news/43070.html

相关文章

Spring Cloud第二季--OpenFeign和Feign

文章目录一、Feign二、Feign和OpenFeign的区别三、案例测试1、eureka注册中心集群7001/70022、两个微服务3、OpenFeign一、Feign Spring Cloud Feign的介绍在Spring Cloud学习–声明式调用&#xff08;Feign&#xff09;中详细介绍。 简单回顾下&#xff0c;Feign是一个声明式…

【音频处理】创建环绕声混响

1D 双声道环绕混响 创建左右声道平衡即可 设置关键帧&#xff1a;全左和全右&#xff0c;拟合方式线性、贝塞尔插值均可 2D 双声道环绕混响 创建2D平面混响&#xff0c;要在一个周期内让声音走完一个360度区域。 我们有两个轴&#xff0c;一个是前后平衡(Forward Backward) …

100Wqps异地多活,得物是怎么架构的?

说在前面 在40岁老架构师尼恩的数千读者群中&#xff0c;一直在指导大家简历和职业升级&#xff0c;前几天&#xff0c;指导了一个华为老伙伴的简历&#xff0c;小伙伴的优势在异地多活&#xff0c;但是在简历指导的过程中&#xff0c;尼恩发现&#xff1a; 异地多活的概念、异…

4.5、协议

4.5、协议1.简介2.常见协议3.UDP协议4.TCP协议5.IP协议6.以太网帧协议7.ARP协议1.简介 协议&#xff0c;网络协议的简称&#xff0c;网络协议是通信计算机双方必须共同遵从的一组约定。如怎么样建立连接、怎么样互相识别等。只有遵守这个约定&#xff0c;计算机之间才能相互通信…

Halo博客建站实战以及问题汇总

目录 简介 特性 快速开始 安装步骤 环境准备 Docker-compose方式部署 问题汇总 mac端无法访问页面 页面登录提示账号密码错误 重装注意点 资料 官方文档 简介 Halo 强大易用的开源建站工具 特性 代码开源 我们的所有代码开源在 GitHub 上且处于积极维护状态&…

百度文心一言与Notion的比较(机器人通信的例子)

文心一言出来有一段时间了&#xff0c;也经常会去问问&#xff0c;感觉对于简单的语义理解还是可以&#xff0c;其答案对于一些常见的常识等还是可以给出不错的答案&#xff0c;但是在数学与代码等方面基本上很差&#xff0c;基本的贷款利率、微积分、没有理解语义的代码等都是…

2023 年 五 大数据恢复软件帮助您找回数据

您是否刚刚丢失了一份需要数天工作才能更换的重要文件&#xff1f;不要恐慌&#xff01;此列表中排名前 10 位的最佳数据恢复软件应用程序可以帮助您找回数据&#xff0c;您甚至可能不必在它们上花任何钱。 五大最佳数据恢复软件工具 以下是我们最喜欢的 10 大数据恢复软件应用…

亚马逊listing如何提高?测评要满足什么条件?

为什么有些大卖就可以卖得很好&#xff0c;而有些卖家始终都做不起来&#xff1f;其中的影响因素之一就是listing&#xff0c;listing页面做得好&#xff0c;转化率自然就提高了。而这其中的原理还需要卖家去具体了解亚马逊的算法。 首先来看一下亚马逊最大的流量搜索&#xf…