Let’s start with the Set parameter

SET key value [EX seconds] [PX milliseconds] [NX|XX]

Associate the string value value with key

If the key
Have a value,
SET
Overwrite the old value, regardless of the type.

For a key with a TTL, when the SET command is successfully executed on the key, the TTL will be cleared.

Optional parameters

SET

  • EX second
    : Sets the expiration time of the key to
    second
    Seconds.
    SET key value EX second 
    Effect of equivalent
    SETEX key second value
    .
  • PX millisecond
    : Sets the expiration time of the key to
    millisecond
    Milliseconds.
    SET key value PX millisecond

    PSETEX key millisecond value

  • NX
    : Sets the key only when the key does not exist.
    SET key value NX 
    Effect equivalent to
    SETNX key value
    .
  • XX
    : Sets a key only when the key already exists.
The return value:

Prior to Redis 2.6.12,

SET

The command always returns
OK.

Starting with Redis 2.6.12,

SET

Returns when the setup operation completes successfully
OK.

If you set it up
NX or
XXThe command returns NULL Bulk Reply, but the setting operation is not executed because the condition is not met.

setnx

The simplest data structure locked in Redis is a string. In the early days, the lock operation used setnx. This command set a val when the lock does not exist. You may remember to use expire to increase the lock expiration.

if(redis.setnx('node:lock', 1)){

     redis.expire('node:lock', 10); / /... todo redis.del('node:lock')}}Copy the code

The problem is that if there is a crash between setnx and EXPIRE, the lock may not be released

set

To solve this problem, we can combine the timeout setting with the set operation

if(redis.set('node:lock', 1,'nx'.'ex', 10)) {/ /... todo redis.del('node:lock')}}Copy the code

The mechanism for acquiring the lock is correct, but the mechanism for removing the lock directly uses del is incorrect. Because it may lead to the error of deleting someone else’s lock.

For example, I keep this lock on for 10 seconds, but IT takes me longer than 10 seconds to process it, and by 10 seconds, the lock automatically expires, is taken away by someone else, and the lock is re-locked. If I call del, I’ll delete the lock that someone else created.



The ultimate version:

function lock(lockName,lockTimeout)){
    let lockKey=lockName+':lock';
    let lockValue=new Date().getTime();
    if(redis.set(lockKey,lockValue, 'nx'.'ex', lockTimeout)){
            return lockValue;
    }
    return null;
}


function unlock(lockName, lockValue)){
    let lockKey=lockName+':lock';
    if(redis.get(lockKey)===lockValue){         redis.del(lockName)
            return true;
        }}
Copy the code

Unlock unlock unlock unlock unlock unlock unlock unlock unlock unlock unlock unlock unlock unlock unlock unlock unlock I shouldn’t have done anything with it.