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
相关推荐
C_Liu_15 分钟前
C++:list
开发语言·c++
my rainy days22 分钟前
C++:友元
开发语言·c++·算法
小梁努力敲代码27 分钟前
java数据结构--List的介绍
java·开发语言·数据结构
摸鱼的老谭1 小时前
构建Agent该选Python还是Java ?
java·python·agent
云知谷1 小时前
【HTML】网络数据是如何渲染成HTML网页页面显示的
开发语言·网络·计算机网络·html
lang201509281 小时前
Spring Boot 官方文档精解:构建与依赖管理
java·spring boot·后端
夫唯不争,故无尤也1 小时前
Tomcat 启动后只显示 index.jsp,没有进入你的 Servlet 逻辑
java·servlet·tomcat
zz-zjx1 小时前
Tomcat核心组件全解析
java·tomcat
Deschen1 小时前
设计模式-外观模式
java·设计模式·外观模式