SET resource-name anystring NX EX max-lock-time 是一种用 Redis 来实现锁机制的简单方法。
The command SET resource-name anystring NX EX max-lock-time is a simple way to implement a locking system with Redis.
A client can acquire the lock if the above command returns OK (or retry after some time if the command returns Nil), and remove the lock just using DEL.
The lock will be auto-released after the expire time is reached.
It is possible to make this system more robust modifying the unlock schema as follows:
1. Instead of setting a fixed string, set a non-guessable large random string, called token.
2. Instead of releasing the lock with DEL, send a script that only removes the key if the value matches.
This avoids that a client will try to release the lock after the expire time deleting the key created by another client that acquired the lock later.
if redis.call("get",KEYS) == ARGV