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

Implementation of distributed Lock in redis

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

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

Editor to share with you the implementation of distributed locks in redis, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

Redis distributed Lock:

1. Realization principle

The distributed lock is realized by using the set command in redis.

Starting with Redis version 2.6.12, set can use the following parameters:

SET KEY VALUE [EX seconds] [PX milliseconds] [NX | XX]

EX second: sets the expiration time of the key to second seconds. The SET key value EX second effect is equivalent to SETEX key second value.

PX millisecond: sets the expiration time of the key to millisecond milliseconds. The SET key value PX millisecond effect is equivalent to PSETEX key millisecond value.

NX: set the key only when the key does not exist. The SET key value NX effect is equivalent to SETNX key value.

XX: set the key only if it already exists.

Return value:

SET returns OK only when the setup operation completes successfully.

If NX or XX is set, but the setting operation is not performed because the condition is not met, the command returns an empty batch reply (NULL Bulk Reply).

Command:

> SET key value EX ttl NX

The general idea is:

(a) SET lock currentTime+expireTime EX 600m NX, use set to set the lock value and set the expiration time to 600s, if successful, acquire the lock

(B) after acquiring the lock, if the node is offline, the ock value will automatically expire at the expiration time.

(C) use del to delete the lock key value when releasing the lock

Using redis stand-alone for distributed locking service may cause a single point of problem, resulting in poor service availability. Therefore, in situations where service stability is high, it is recommended to use redis clusters (for example, 5 redis clusters are considered to be acquired if more than 3 locks are successfully requested) to implement redis distributed locking. See RedLock for details.

2. Advantages

High performance, redis can be persisted, and data is not easy to lose.

Redis cluster mode improves stability.

3. Shortcomings

Some data may be lost when using redis master-slave switching.

4. Open source implementation

Open source implementation of the python version: python-redis-lock.

The specific implementation of redis distributed lock:

How to lock and unlock:

Private static final String LOCK_SUCCESS = "OK"; private static final String SET_IF_NOT_EXIST = "NX"; private static final String SET_WITH_EXPIRE_TIME = "PX"; private static final Long RELEASE_SUCCESS = 1L / * attempt to acquire distributed lock * @ param lockKey lock * @ param requestId request ID * @ param expireTime timeout * @ return obtained successfully * / public Boolean tryGetDistributedLock (String lockKey, String requestId, int expireTime) {Jedis jedis = this.jedisPool.getResource () String result = jedis.set (lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime); if (LOCK_SUCCESS.equals (result)) {return true;} return false } / * * release distributed lock * @ param lockKey lock * @ param requestId request identifies whether * @ return has been released successfully * / public Boolean releaseDistributedLock (String lockKey, String requestId) {Jedis jedis = this.jedisPool.getResource () String script = "if redis.call ('get', KEYS [1]) = ARGV [1] then return redis.call (' del', KEYS [1]) else return 0 end"; Object result = jedis.eval (script, Collections.singletonList (lockKey), Collections.singletonList (requestId)); if (RELEASE_SUCCESS.equals (result)) {return true;} return false;}

2. Specific application

Try {String requestId = UUID.randomUUID (). ToString (); Boolean flag = tryGetDistributedLock (lock,requestId,1000); int n = 0 position while (! flag) {/ / if no lock is acquired, you can try the next lock, if none, try n times, exit. If (nasty + > 5) {throw new Exception ("attempt to acquire lock failed");}} if (! flag) {throw new Exception ("failed attempt to acquire lock");}} catch () {} finally {releaseDistributedLock (lock,requestId);} above is all about the implementation of distributed locks in redis. Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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