Application scenarios of distributed locks: With the development of services, single applications become clusters, distributed locks solve the operation of different processes (threads) on the same resource in concurrent situations, and some services must require a single thread to operate, for example: changes in deposit amounts, changes in commodity inventory, etc.
Review:
In the previous article "[Practice]ASP.NET Core Based on Redis Distributed Lock Flash Kill", when we added a lock, we also enabled a background thread to extend the lock time, so as to ensure that when the lock is released, the lock occupied by other threads will not be mistakenly deleted.
After learning Redis to use Lua scripts, you can easily use scripts to complete occupancy locks and release locks.
First, let's take a look at the renderings as follows:
We first opened 1000 parallel threads to compete for the lock, and the lock expired for 5 seconds.We completed 1000 threads in 5 seconds, and only 1 thread successfully acquired the lockAfter waiting for 6 seconds, the lock will be automatically released, and you can see that the second task has successfully obtained the lock, and immediately released the lock, and the subsequent code has successfully obtained the lock.
The lua script to get the lock is as follows:
The lua script to release the lock is as follows:
Interface code:
Source code download:The hyperlink login is visible.
Modify "[Practice] ASP.NET Core based on Redis distributed lock flash sale" is implemented using this article, and our website simulates it10000 items, and then wrote a console to simulate the HTTP request timeThe sold-out is completed in 6 seconds, as shown in the figure below:
Modify the test simulation request code:
(End)
|