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

// 设置键值
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. 上述代码中使用的方法是覆盖写入,从指定偏移量开始覆盖写入字符串,不是用来设置过期时间的
void set(K key, V value,
long offset)
;
  1. 应该使用的方法是存储键值对并设置过期时间
void set(K key, V value,
long timeout, TimeUnit unit)
;
处理策略
  • 使用存储键值对并设置过期时间方法
// 设置键值
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
posted @ 2025-07-20 08:06  yjbjingcha  阅读(12)  评论(0)    收藏  举报