redis 中setex、setnx、set、getset 命令的區別與使用


 

介紹幾個常用的redis命令:

SET 命令

set key value

設置指定 key 的值為 value。

如果 key 已經存儲其他值, SET 就覆寫舊值,且無視類型。

127.0.0.1:6379> set testSetKey aaa
OK
127.0.0.1:6379> get testSetKey
"aaa"
127.0.0.1:6379> set testSetKey bbb  # 會覆寫舊值
OK
127.0.0.1:6379> get testSetKey
"bbb"

 

SETEX 命令

setex key seconds value

設置指定 key 的值為 value,並將 key 的過期時間設為 seconds (以秒為單位)。

如果 key 已經存在, SETEX 命令將會替換舊的值。

127.0.0.1:6379> setex testSetexKey 60 aaa   # 設置過期時間為60秒
OK
127.0.0.1:6379> get testSetexKey   # 有效期內獲取
"aaa"
127.0.0.1:6379> get testSetexKey   # 時間過期后再次獲取返回 nil
(nil)
127.0.0.1:6379> setex testSetexKey 60 aaa
OK
127.0.0.1:6379> get testSetexKey
"aaa"
127.0.0.1:6379> setex testSetexKey 60 bbb    # 替換舊值
OK
127.0.0.1:6379> get testSetexKey
"bbb"

 

SETNX 命令

setnx key value

設置指定 key 的值為 value,只有在 key 不存在時設置 key 的值。

setnx(SET if Not eXists) 命令在指定的 key 不存在時,為 key 設置指定的值。

設置成功,返回 1 。 設置失敗,返回 0 。

127.0.0.1:6379> setnx testSetnxKey aaa
(integer) 1
127.0.0.1:6379> get testSetnxKey
"aaa"
127.0.0.1:6379> setnx testSetnxKey bbb  # 當key值存在時,返回0
(integer) 0
127.0.0.1:6379> get testSetnxKey
"aaa"

 

GETSET 命令

getset key value

設置指定 key 的值為 value,並返回 key 的舊值(old value)。

返回給定 key 的舊值。 當 key 沒有舊值時,即 key 不存在時,返回 nil 。

當 key 存在但不是字符串類型時,返回一個錯誤。

127.0.0.1:6379> getset testGetsetKey aaa  # 沒有舊值時,返回 nil
(nil)
127.0.0.1:6379> get testGetsetKey
"aaa"
127.0.0.1:6379> getset testGetsetKey bbb  # 返回舊值
"aaa"
127.0.0.1:6379> get testGetsetKey
"bbb"

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM