The difference and use of setex, setnx, set and GetSet commands in redis

Time:2021-2-25

 

This paper introduces several common redis commands

Set command

set key value

Set the value of the specified key to value.

If the key has already stored other values, set will override the old value and ignore the type.

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 # will override the old value
OK
127.0.0.1:6379> get testSetKey
"bbb"

 

Setex command

setex key seconds value

Set the value of the specified key to value, and set the expiration time of the key to seconds (in seconds).

If the key already exists, the setex command will replace the old value.

127.0.0.1:6379 > setex testsetexkey 60 AAA ා set the expiration time to 60 seconds
OK
127.0.0.1:6379 > get testsetexkey #
"aaa"
127.0.0.1:6379 > get testsetexkey # get nil again after time expired
(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 # replace old value
OK
127.0.0.1:6379> get testSetexKey
"bbb"

 

Setnx command

setnx key value

Set the value of the specified key to value. Set the value of the key only when the key does not exist.

The setnx (set if not exists) command sets the specified value for the key when the specified key does not exist.

Set successfully, return 1. Failed to set, return 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 # when the key value exists, it returns 0
(integer) 0
127.0.0.1:6379> get testSetnxKey
"aaa"

 

GetSet command

getset key value

Set the value of the specified key to value, and return the old value of the key.

Returns the old value of the given key. When the key has no old value, that is, the key does not exist, nil is returned.

Returns an error when the key exists but is not of string type.

127.0.0.1:6379 > GetSet testgetsetkey AAA # when there is no old value, nil is returned
(nil)
127.0.0.1:6379> get testGetsetKey
"aaa"
127.0.0.1:6379 > GetSet testgetsetkey BBB # returns the old value
"aaa"
127.0.0.1:6379> get testGetsetKey
"bbb"

 

Recommended Today

Third party calls wechat payment interface

Step one: preparation 1. Wechat payment interface can only be called if the developer qualification has been authenticated on wechat open platform, so the first thing is to authenticate. It’s very simple, but wechat will charge 300 yuan for audit 2. Set payment directory Login wechat payment merchant platform( pay.weixin.qq . com) — > Product […]