Redis Lock
Redis is a single process single-threaded mode that uses queue mode to turn concurrent access into serial access, and there is no competitive relationship between multiple clients for Redis connections.
SETNX command (SET if not eXists) syntax:
Setnx Key value
If a given key already exists, SETNX does nothing and returns 0.
Security: guarantees mutual exclusion , at any time, only one client can hold the lock
No deadlock: Even if the client currently holding the lock crashes or is separated from the cluster, the other clients will always be able to acquire the lock.
Fault tolerance: As long as most of the Redis nodes are online, the client can acquire and release the lock. Lock:
if (Conn.setnx ("Lock", "1"). Equals (1L)) {return
true;
}
return false;
Unlock
Conn.del ("lock");
There is a problem: the client crashes or otherwise causes the unlock to fail, and other clients will no longer be able to acquire the lock, causing the deadlock.
SET resource_name my_random_value NX PX 30000
The NX in the command indicates that if the key does not exist, it is added, and the presence is returned directly.
PX Indicates the expiration time of the key in milliseconds, which is 30000ms.
Setting the expiration time is to prevent a client from acquiring a lock from suddenly collapsing or other unusual circumstances, causing the object lock in the Redis to be unable to release, causing the deadlock. The value of the key needs to be guaranteed to be a unique value in all clients requesting the lock service. This is to ensure that the client who gets the lock can safely release the lock, preventing the lock object from being deleted by another client. Distributed Locks
Example: A client gets the object lock but is blocked for some reason and cannot release the lock in time. The lock object in Redis has been deleted because the expiration time has expired.
The B client requested to acquire the lock successfully.
C Client request fetch lock succeeded.
Both B and C got the lock, so the distributed lock failed. Lock:
public static string lock (String lockname, long lockTimeout) {
string identifier = Uuid.randomuuid (). toString ();
if (Redis.setnx (Lockname, identifier). Equals (1L)) {
Redis.pexpire (lockname, lockTimeout);
} else if ( Redis.ttl (Lockname). Equals ( -1l)) {
Redis.pexpire (lockname, lockTimeout);
return null;
}
Unlock:
public static void Unlock (string lockname, string identifier) {
if (identifier.equals (Redis.get (lockname))) {
Redis.del (lockname);
}
Lock parameter meaning: Keys[1]: Need to lock the key, here needs to be a string type.
ARGV[1]: Lock timeout to prevent deadlock
ARGV[2]: The unique identification of the lock, which is just the ID (uuid.randomuuid ()) + ":" + threadId
Check if key is already in use, and if not, set timeout time and unique identity, initialize value=1
if (Redis.call (' exists ', keys[1]) = = 0)
then
redis.call (' Hset ', keys[1], argv[2], 1)
; Redis.call (' Pexpire ', keys[1], argv[1]);
return nil;
End If the lock is reentrant, it is necessary to determine that the key field of the lock is consistent with the value plus one
if (Redis.call (' hexists ', keys[1], argv[2]) = = 1)
then Redis.call
(' Hincrby ', keys[1], argv[2], 1);
Redis.call (' Pexpire ', keys[1], argv[1);//Lock re-enter Reset timeout time return
nil;
End Returns the remaining expiration time return
redis.call (' Pttl ', keys[1]);
Unlock
Parameters:
–KEYS[1]: Key that needs to be locked, here needs to be a string type.
–KEYS[2]: Redis message ChannelName, a distributed lock corresponds to the only one
ChannelName: "redisson_lock__channel__{" + getName () + "}"
–ARGV[1]: Reids message body, here only need a byte of the tag can be, the main tag Redis key has been unlocked, combined with Redis subscribe, can wake up other subscribing to unlock the message of the client thread to request a lock.
–ARGV[2]: Lock timeout, prevent deadlock –argv[3]: Unique identification of the lock, which is the ID (uuid.randomuuid ()) + ":" + threadId
If the key is no longer present, the description has been unlocked, direct Publishing (publish) Redis message
if (Redis.call (' exists ', keys[1]) = = 0)
redis.call (' Publish ', keys[2], argv[1]);
return 1;
End Key and field mismatch, indicating that the current client thread does not hold a lock and cannot actively unlock it.
if (redis.call (' hexists ', keys[1], argv[3]) = = 0)
then return nil;
End
Subtract value by 1
Local counter = Redis.call (' Hincrby ', keys[1], argv[3],-1); If the counter>0 indicates that the lock is in reentrant, you cannot delete the key
if (Counter > 0)
then Redis.call (' Pexpire ', keys[1], argv[2]);
return 0;
else//delete key and publish unlock message
redis.call (' del ', Keys[1]);
Redis.call (' Publish ', keys[2], argv[1]);
return 1;
End;
return nil;
the high-performance lock, unlock section uses LUA encapsulation to ensure atomicity.
Use the PUB/SUB message mechanism to reduce the wait time for lock requests security locks with timeout time, lock identification unique, prevent deadlock design to be reentrant, avoid deadlock
Reentrant locks refer to the same locks that can be acquired multiple times in a single thread, such as the Reentrantlock and synchronized keywords in Java
public void Get () {lock.lock ();
Set ();
Lock.unlock ();
public void Set () {Lock.lock (); Lock.unlock (); }