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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值