The evolution of technology is all about solving problems, which is also an attractive point of technological evolution.
Redis distributed lock
As the name implies, distributed locks mean that multiple machines compete for a resource to lock in a distributed scenario.
the simplest version
The first is the simplest version, you can use the setnx command of Redis (set if not exist)
setnx key value
This command will create a key with a value of value if the key does not exist in Redis, and return 0 if it exists
Expiration
What if the machine service that acquires the lock hangs up?
Other machines: Why doesn't grandma drop release the lock?
So there is a back-and-forth strategy: set the expiration time (the lock will automatically expire and be released after a period of time after hanging up)
At this point, you can use an atomic operation command that comes with Redis:
setnx key value nx ex 100
The unit of time is seconds
What if the wrong lock is released?
Look at such a scene:
Two issues are involved:
- The task expires and releases the lock before it finishes processing
- released someone else's lock
Corresponding solutions:
- Renewal of the lock (extend the time according to the business, and access the lock every time, if it exists, renew the contract and increase the time)
- Distinguish each lock, who added the lock (the value of the lock can be set to a uniquely determined value such as UUID)
After optimization:
Lua achieves atomicity
What happens when the above step is deleted?
Of course, this problem has been solved above, that is, UUID + thread id is used as the key, and it will not be deleted by other threads, but it seems that this kind of error is also quite dangerous. As a bottom-up solution, we can use lua scripts to achieve atomicity
Lua scripts can be written like this
last defense
Of course, the distributed NPC principle tells us that there is no completely safe distributed lock (so everyone still has to do it according to the business)
In the above scenario, what should I do if the master node is down?
Because Redis is based on AP architecture, that is to say, high consistency cannot be guaranteed, and the lock in the master node may not be synchronized to the slave node.
Here you can use the official Redis Red Lock to ensure that the master and slave of the node selected by the current hash algorithm have keys before returning true
This approach is also a bit "heavy". Sometimes, killing a chicken with a bull's knife