Spring Boot 项目集成 Redis 问题:RedisTemplate 多余空格问题

java 复制代码
// 设置键值
redisTemplate.opsForValue().set("name", "张三");

// 设置带过期时间的键值
redisTemplate.opsForValue().set("temp_key", "临时值", 60);

// 获取值
String name = (String) redisTemplate.opsForValue().get("name");
System.out.println(name);
System.out.println(name.length());
String tempKey = (String) redisTemplate.opsForValue().get("temp_key");
System.out.println(tempKey);
System.out.println(tempKey.length());
复制代码
# 输出结果

张三
2
                                                            临时值
63
  • 在 Spring Boot 项目中,使用 spring-boot-starter-data-redis 时,输出结果出现多余的空格
问题原因
  1. 上述代码中使用的方法是覆盖写入,从指定偏移量开始覆盖写入字符串,不是用来设置过期时间的
java 复制代码
void set(K key, V value, long offset);
  1. 应该使用的方法是存储键值对并设置过期时间
java 复制代码
void set(K key, V value, long timeout, TimeUnit unit);
处理策略
  • 使用存储键值对并设置过期时间方法
java 复制代码
// 设置键值
redisTemplate.opsForValue().set("name", "张三");

// 设置带过期时间的键值
redisTemplate.opsForValue().set("temp_key", "临时值", 60, TimeUnit.SECONDS);

// 获取值
String name = (String) redisTemplate.opsForValue().get("name");
System.out.println(name);
System.out.println(name.length());
String tempKey = (String) redisTemplate.opsForValue().get("temp_key");
System.out.println(tempKey);
System.out.println(tempKey.length());
复制代码
# 输出结果

张三
2
临时值
3
相关推荐
编码浪子2 小时前
趣味学RUST基础篇(智能指针_结束)
开发语言·算法·rust
七夜zippoe3 小时前
事务方案选型全景图:金融与电商场景的实战差异与落地指南
java·分布式·事务
CVer儿4 小时前
qt资料2025
开发语言·qt
杨二K4 小时前
认识HertzBeat的第一天
java·hertzbeat
DevilSeagull4 小时前
JavaScript WebAPI 指南
java·开发语言·javascript·html·ecmascript·html5
2zcode4 小时前
基于Matlab不同作战类型下兵力动力学模型的构建与稳定性分析
开发语言·matlab
二掌柜,酒来!5 小时前
完美解决:应用版本更新,增加字段导致 Redis 旧数据反序列化报错
redis·spring·bootstrap
期待のcode6 小时前
Spring框架1—Spring的IOC核心技术1
java·后端·spring·架构
鼠鼠我捏,要死了捏6 小时前
Spring Boot Actuator自定义指标与监控实践指南
spring boot·监控·actuator
葵野寺6 小时前
【RelayMQ】基于 Java 实现轻量级消息队列(七)
java·开发语言·网络·rabbitmq·java-rabbitmq