Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Simple implementation method of distributed Lock based on Redis

2025-04-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

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.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report