打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
解决使用redisTemplate set方法保存出现\x00\问题

在项目有个需求要保存一个字符串到redis,并设置一个过期时间。这个需求一看非常简单,使用redisTemplate一行代码搞定,代码如下

redisTemplate.opsForValue().set("userKey", data, 10000); 

但保存后,查看redis发现value的前缀多出了

\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x

一开始以为是redis的序列化问题,于是就修改了redisTemplate的序列化方式,终于还是没能解决问题。那问题出在哪里?翻看源码,发现redisTemplate.opsForValue().set()有重载方法,一个是

void set(K key, V value, long offset) 

另外一个是

void set(K key, V value, long timeout, TimeUnit unit)

调用set(K key, V value, long offset)这个方法,其底层调用的是redis的setrange命令,这个命令看官网介绍

Overwrites part of the string stored at key, starting at the specified offset, for the entire length of value. If the offset is larger than the current length of the string at key, the string is padded with zero-bytes to make offset fit. Non-existing keys are considered as empty strings, so this command will make sure it holds a string large enough to be able to set value at offset

其含义是从指定的偏移量开始,覆盖整个值范围内从key存储的字符串的一部分。如果偏移量大于key处字符串的当前长度,则该字符串将填充零字节以使偏移量适合。不存在的键被视为空字符串,因此此命令将确保它包含足够大的字符串以能够将值设置为offset。

调用set(K key, V value, long timeout, TimeUnit unit)这个方法,其底层调用的是redis命令setex。这个命令看官网介绍

Set key to hold the string value and set key to timeout after a given number of seconds

很显然这个方法,才是我们真正想要的方法。因此解决使用restemplate set方法保存出现\x00\问题的方案就是使用

void set(K key, V value, long timeout, TimeUnit unit)

这个方法

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
java架构师-技术专家-练习手册-第07周 分布式redis
Redis所支持的数据结构
Redis系列~字符串(String)(六)
SpringBoot中Redis的set、map、list、value、实体类等基本操作介绍
Java封装redis工具类
springboot之使用redistemplate优雅地操作redis
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服