Home >Database >Redis >Why can redis do distributed locks?

Why can redis do distributed locks?

(*-*)浩
(*-*)浩Original
2019-11-21 13:43:077328browse

Why can redis do distributed locks?

#Redis is a single-process single-thread mode. It uses queue mode to turn concurrent access into serial access, and there is no competition between multiple clients' connections to Redis.

What the code implements is mainly to lock the serial number of a certain piece of data to prevent multiple threads from writing this data. (Mutually exclusive) (Recommended learning: Redis video tutorial)

The most popular redis distributed lock now is Redisson, let’s take a look at its underlying layer The principle is to understand how redis uses distributed locks

Why can redis do distributed locks?Principle analysis

What distributed locks need to solve is in a distributed environment. Parallel locking function of the same code; those who have learned about redis distributed locks must know that redis initially used setnx as a distributed lock, and then set a scheduled expiration time on this basis. But what are the problems with this method?

In fact, people who understand the above picture will understand what the problem is. The first is the atomicity problem. The two operations of setnx expiration time must be atomic, so this can be solved with Lua script

Then how to determine the timing of releasing the lock?

No matter how much expiration time we set, there is no guarantee that the locked code will be executed during this period, so it is not good to set this time;

If it is not determined time, when the execution is completed, the lock is released. The problem is that if the machine crashes halfway through the execution, the lock will never be released.

So how does Redisson solve the above problem?

It simplifies the code encapsulation, our use is very simple, we don’t even need to actively set the expiration time

It designs a watch dog watchdog, every 10 The second will check whether the lock is still held. If it holds the lock, it will update the expiration time for 30 seconds. Through this design, it can keep holding the lock until it releases the lock. Even if it is down, it can automatically The client that releases the lock

but cannot obtain the lock will continuously try to acquire the lock in a loop

By recording the client ID of the lock, it can be designed as a reentrant lock

Why can redis do distributed locks?

The above is the detailed content of Why can redis do distributed locks?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Why is redis fast?Next article:Why is redis fast?