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
时,输出结果出现多余的空格
问题原因
- 上述代码中使用的方法是覆盖写入,从指定偏移量开始覆盖写入字符串,不是用来设置过期时间的
void set(K key, V value,
long offset)
;
- 应该使用的方法是存储键值对并设置过期时间
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