In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
Editor to share with you how to use redis to achieve distributed locks, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
1. Add lock
The easiest way is to use the setnx command. Key is the unique identification of the lock, which is named according to the business. For example, if you want to lock the flash sale activity of a commodity, you can name key "lock_hot_ merchandise ID". And what is value set to? We can set it to 1 for a while. The pseudo code for locking is as follows:
Setnx (key,1)
When a thread executes setnx and returns 1, it means that key does not exist and the thread successfully gets the lock; when a thread executes setnx and returns 0, it means that key already exists and the thread fails to grab the lock.
two。 Unlock
If you have a lock, you have to unlock it. When the thread that gets the lock finishes the task, the lock needs to be released so that other threads can enter. The easiest way to release the lock is to execute the del instruction, the pseudo code is as follows:
Del (key)
After the lock is released, other threads can continue to execute the setnx command to acquire the lock.
3. Lock timeout
What does lock timeout mean? If a thread that gets the lock dies during the execution of the task and has no time to explicitly release the lock, the resource will be locked forever and no other thread will ever come in.
Therefore, setnx's key must set a timeout to ensure that the lock is automatically released after a certain period of time, even if it is not explicitly released. Setnx does not support timeout parameters, so additional instructions are required
The pseudo code is as follows:
Expire (key, 30) 4. Comprehensive analysis
The first version of our distributed lock implementation's pseudo code is as follows:
If (setnx (key,1) = = 1) {expire (key,30) try {do something. } finally {del (key)}}
In the pseudo code above, there are three fatal problems:
1. Non-atomicity of setnx and expire
Imagine an extreme scenario where when a thread executes setnx, it successfully gets the lock:
Setnx has just been executed successfully, and before it has time to execute the expire instruction, node 1 Duang hangs up.
In this way, the lock does not set an expiration time, becomes "immortal", and other threads can no longer acquire the lock.
How to solve it? The setnx instruction itself does not support passing the timeout, but Redis version 2.6.12 and above adds optional parameters to the set directive. The pseudo code is as follows:
Set (key,1,30,NX)
This replaces the setnx instruction.
2. Del causes erroneous deletion
Another extreme scenario, if a thread succeeds in getting the lock and sets a timeout of 30 seconds.
If thread An executes slowly for some reason and does not finish execution after 30 seconds, the lock expiration is automatically released and thread B gets the lock.
Thread A then finishes executing the task, and thread A then executes the del instruction to release the lock. But at this time, thread B has not finished execution, thread An actually removes the lock added by thread B.
How to avoid this situation? You can make a decision before del releases the lock to verify that the current lock is self-imposed.
As for the specific implementation, you can treat the current thread ID as a value when locking, and verify that the corresponding value of the key is the ID of your own thread before deleting it.
Lock:
String threadId = Thread.currentThread (). GetId () set (key,threadId, 30 Magi NX)
Unlock:
If (threadId .equals (redisClient.get (key) {del (key)}
However, this implies a new problem: judging and releasing locks are two independent operations, not atomicity.
We are all extreme programmers, so this piece should be implemented in Lua scripts:
String luaScript = "if redis.call ('get', KEYS [1]) = ARGV [1] then return redis.call (' del', KEYS [1]) else return 0 end"; redisClient.eval (luaScript, Collections.singletonList (key), Collections.singletonList (threadId))
In this way, the validation and deletion process is an atomic operation.
3. The possibility of concurrency
It is still the scenario described in the second point just now. Although we avoid thread A mistakenly deleting key, it is still not perfect to have two threads, An and B, accessing the code block at the same time.
What should I do? We can ask the thread that acquired the lock to open a daemon thread to "renew" the lock that is about to expire.
When 29 seconds have elapsed and thread A has not finished executing, the daemon will execute the expire instruction to "renew" the lock for 20 seconds. The daemon thread starts execution in 29 seconds and executes every 20 seconds.
When thread A finishes the task, it explicitly shuts down the daemon thread.
On the other hand, if Node 1 suddenly loses power, the daemon thread will stop because thread An and the daemon thread are in the same process. When the lock is out of time, no one will renew its life, so it will be released automatically.
The above is all the content of the article "how to use redis to implement distributed locks". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.