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

发布于:2025-06-08 ⋅ 阅读:(20) ⋅ 点赞:(0)
// 设置键值
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

网站公告

今日签到

点亮在社区的每一天
去签到