In business scenarios, simultaneous operations of content, such as commodity inventory, the same file, etc., are not allowed, and the program application is deployed on multiple servers.
The previously written zk-based distributed lock is as follows:
What you also need to know to read this article:
.NET Core implements distributed locks based on RedisThe principle is to call the SETNX command of redis, if the key already exists, the SETNX command does nothing. The command returns 1 when the setting succeeds and 0 when the setting fails.
The hyperlink login is visible.
Create a new .NET Core 3.1 console project, add a StackExchange.Redis reference, and use the nuget command as follows:
We call the library's StringSet method, through the StackExchange.Redis source code, we can see that the StringSet method will call the private method of GetStringSetMessage to execute different set commands through the enumeration value of when, the code is as follows:
We execute the SETNX command 2000 times through a parallel test call to the program, which is executed in 2 installments, in which the cache validity of the key is 5 seconds, that is, the key will be automatically released after 5 seconds, that is, the lock will be released.
The code is as follows:
As you can see, a total of 2 successful insertions and 1998 failed attempts are exactly what we expected, and the renderings are as follows:
At this time, the lock has not yet been released. (End)
|