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
相关推荐
新手小新30 分钟前
C++游戏开发(2)
开发语言·前端·c++
Code blocks1 小时前
关于“LoggerFactory is not a Logback LoggerContext but Logback is on ......“的解决方案
java·spring boot·后端
你的电影很有趣1 小时前
lesson30:Python迭代三剑客:可迭代对象、迭代器与生成器深度解析
开发语言·python
飞翔的佩奇1 小时前
基于SpringBoot+MyBatis+MySQL+VUE实现的经方药食两用服务平台管理系统(附源码+数据库+毕业论文+部署教程+配套软件)
数据库·vue.js·spring boot·mysql·毕业设计·mybatis·经方药食两用平台
bing_1582 小时前
在多租户或多服务共享 Redis 时,如何做逻辑隔离或权限控制?
数据库·redis·缓存
程序员编程指南2 小时前
Qt 嵌入式界面优化技术
c语言·开发语言·c++·qt
q__y__L3 小时前
C#线程同步(二)锁
开发语言·性能优化·c#
二川bro3 小时前
第二篇:Three.js核心三要素:场景、相机、渲染器
开发语言·javascript·数码相机
云泽8083 小时前
数据结构前篇 - 深入解析数据结构之复杂度
c语言·开发语言·数据结构
卷卷的小趴菜学编程4 小时前
Qt-----初识
开发语言·c++·qt·sdk·qt介绍