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 redis distributed Lock in Java

2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article mainly introduces "the implementation method of redis distributed lock in Java". In the daily operation, I believe that many people have doubts about the implementation method of redis distributed lock in Java. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubt about "the implementation method of redis distributed lock in Java". Next, please follow the editor to study!

Redis distributed Lock 1. What is a distributed lock?

Distributed locks are used to solve the problems caused by multiple processes mutually exclusive access to shared resources.

For example, when you do a new operation, in order to prevent repeated insertion, you need to make a logical judgment of "find-> whether it exists-> do not exist-> add".

If two threads enter this logical judgment at the same time, there will be two insert operations when both threads enter the judgment that "does not exist" at the same time.

Generally speaking, in order to solve this problem, thread-safe methods such as synchronized can be used in Java, but when the application is multi-instance deployment, distributed locks are needed to solve it.

two。 What are the distributed locks?

1. Based on database

two。 Based on redis

3. Based on middleware (zookeeper)

3. Conditions for using distributed locks

The use of distributed locks requires the following three conditions

1. Mutually exclusive. That is, the lock can only be obtained by one thread.

two。 No deadlock. Thread crash and other reasons lead to a long time to acquire the lock will not be released, there must be a mechanism to automatically release the lock.

3. Don't misunderstand the lock. Locking and unlocking must be the same thread.

The principle of 4.redis distributed Lock

Why use redis as a distributed lock?

The main reason is that the redis is accessed by a single thread, and the instructions are executed one by one in the queue.

All we need to do is write a script to lock the operation and let redis execute it.

5. Specific steps 5.1. Get lock object

The lock object includes two values, key and requestId.

Key is the key of the lock, which is usually the scene + unique ID

RequestId is the value of the lock, which is used to ensure that the lock will not be unlocked by mistake, usually with a key+ timestamp.

Public RedisLockBean getLockBean (String lock, String id) {String LockKey = lock.concat (id); String requestId = LockKey.concat (String.valueOf (System.currentTimeMillis (); return new RedisLockBean (). SetKey (LockKey) .setRequestId (requestId);} 5.2. Add lock

Use code to execute commands

SET key requestId NX PX 10000

NX: set it if it doesn't exist

PX milliseconds: the expiration time of the key is set to how many milliseconds

Private static final String SET_IF_ABSENT = "NX"; private static final String SET_WITH_EXPIRE_TIME = "PX"; private Long expireTime = 10000L connection public Boolean setLock (RedisLockBean lockBean) {RedisCallback stringRedisCallback = (connection)-> {JedisCommands commands = (JedisCommands) connection.getNativeConnection (); return commands.set (lockBean.getKey (), lockBean.getRequestId (), SET_IF_ABSENT, SET_WITH_EXPIRE_TIME, expireTime);}; String result = (String) redisTemplate.execute (stringRedisCallback) Return! StringUtils.isEmpty (result);} 5.3. Determine whether the lock is acquired, and if not, it can be looped or an exception is thrown. 5.4. Unlock

Execute a command

If redis.call ("get", KEYS [1]) = ARGV [1] then return redis.call ("del", KEYS [1]) else return 0endprivate static final String UNLOCK_LUA;static {StringBuilder sb = new StringBuilder (); sb.append ("if redis.call (\" get\ ", KEYS [1]) = = ARGV [1]"); sb.append ("then"); sb.append ("return redis.call (\" del\ ", KEYS [1])") Sb.append ("else"); sb.append ("return 0"); sb.append ("end"); UNLOCK_LUA = sb.toString () } public Boolean releaseLock (RedisLockBean lockBean) {/ / when releasing the lock, it is possible that try {List keys = new ArrayList (); keys.add (lockBean.getKey ()); List args = new ArrayList (); args.add (lockBean.getRequestId ()) cannot be deleted directly because the execution time of the method after the lock is longer than the validity period of the lock. / / use lua script to delete key matching value in redis to avoid mistakenly deleting locks of other threads when the redis lock expires automatically due to too long execution time. / / in the execution script method included with spring, cluster mode directly throws an exception that does not support script execution. So you can only get the connection of the original redis to execute the script RedisCallback callback = (connection)-> {Object nativeConnection = connection.getNativeConnection () / / Cluster mode and stand-alone mode have the same method of executing scripts, but do not have a common interface, so they can only execute / / cluster mode if (nativeConnection instanceof JedisCluster) {return (Long) ((JedisCluster) nativeConnection) .eval (UNLOCK_LUA, keys, args) separately. } / / standalone mode else if (nativeConnection instanceof JedisCommands) {return (Long) ((Jedis) nativeConnection) .eval (UNLOCK_LUA, keys, args);} return 0L;}; Long result = (Long) redisTemplate.execute (callback); return result! = null & & result > 0 } catch (Exception e) {log.error ("release lock occured an exception", e);} return false;} at this point, the study on "the implementation of redis distributed locks in Java" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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

Internet Technology

Wechat

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

12
Report