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
相关推荐
苏三说技术1 小时前
LangChain4j 和 LangGraph4j,哪个更好?
后端
ServBay2 小时前
7 个AI开发中真正用得上的 MCP Server,配合Claude Code食用效果更佳
后端·claude·mcp
妙码生花2 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十五):优化细节、网络请求封装
前端·后端·ai编程
用户6757049885023 小时前
Go 语言里判断字符串为空,90% 的人都写错了!
后端·go
Flittly3 小时前
【AgentScope Java新手村系列】(16)从RAG到多路检索
java·spring boot·spring
用户6757049885023 小时前
Go 进阶必修:90% 的人都没用对的“表驱动法”
后端·go
小兔崽子去哪了3 小时前
Java 生成二维码解决方案
java·后端
苍何3 小时前
懂事的 Agent 已经开始自己看屏幕干活了,效率起飞!
后端
掘金码甲哥4 小时前
1分钟买不了吃亏系列: nginx动态域名解析
后端