Since it is a lock, the first function that comes to mind is: Anti-repeated clicks, only one request has an effect at a time.
Since it is
redis, it must be exclusive and also have some common features of locks:
- High performance
- No deadlock
- No lock failure after the node is down
set key nx can be used to ensure that the write is successful when the key does not exist.
px can automatically delete the key after the timeout. "The worst case is that the key is automatically deleted after the timeout, so that there will be no death. lock"
It is the same as when you use
sync.Mutex. Lock and unlock, perform your business operations.
First introduce several
redis command options, the following are the added options for the
ex seconds: Set the key expiration time, in s
px milliseconds: set the key expiration time in milliseconds
nx: When the key does not exist, set the value of the key
xx: When the key exists, the value of the key will be set
The input parameters involved in
|ARGV||lmnopqrstuvwxyzABCD||Unique ID: random string|
|ARGV||30000||Set the expiration time of the lock|
Then talk about the code features:
Luascript guarantees atomicity "Of course, multiple operations are implemented as one operation in Redis, that is, a single command operation"
set key value px milliseconds nx
- When locking, first determine whether the
keyis consistent with the previous setting, and modify the expiration time if it is consistent
You only need to pay attention to one point when releasing the lock:
Can't release other people's locks, can't release other people's locks, can't release other people's locks
Therefore, you need to first
get(key) == value「key」, and then go to
delete if it is true