亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

解決使用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)

这个方法

點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
JAVA開發工程師
手記
粉絲
7
獲贊與收藏
23

關注作者,訂閱最新文章

閱讀免費教程

  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消