Get the App
SLTechnology News&Howtos  ›  Database  › 

Simple implementation method of distributed Lock based on Redis

Shulou Source: shulou.com Published: 2022-06-01 03:44:39 10月01日 Update

Redis officials give two ideas.

The first kind: SET key value [EX seconds] [PX milliseconds] NX

The second kind: SETNX+GETSET

First of all, take a look at these commands separately.

SET command

SETNX command

GETSET command

Next, look at the first way.

The official idea is like this.

There's another thing, it's similar.

This approach may be implemented as follows:

The second way

The official idea is like this.

The code might look like this.

Summary:

The basic idea of both methods is that the client sets a key value on the server, which is considered to be successful if it can be set successfully, and the deletion of key means unlocking.

The difference is that the SET method only needs to determine whether the setting is successful or not, and whether it is set by yourself when deleting it. In case of a timeout, the lock can be automatically released by using the survival time of the system itself.

In addition to judging whether the setting is successful or not, the SETNX+GETSET method needs to further determine whether the value is valid when the setting fails, and it is up to the client to judge whether it times out or not.

Reference https://redis.io/topics/distlock

The above is the whole content of this article, I hope it will be helpful to your study, and I also hope that you will support it.

Tags: Way success command train of thought official client client time different valid code content just that is time server system enter one reference learning Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Redmi NVidia Shulou Tech Info Apple