Quickly understand Redis distributed locks in vernacular

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

image.png

Expiration

What if the machine service that acquires the lock hangs up?

image.png

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:

image.png

Two issues are involved:

  1. The task expires and releases the lock before it finishes processing
  2. released someone else's lock

Corresponding solutions:

  1. 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)
  2. 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:

image.png

Lua achieves atomicity

What happens when the above step is deleted?

image.png

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

7e5cc0a8898c93381a90dbb81b414cc8.png

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

Guess you like

Origin juejin.im/post/7255902957035323450