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

How to implement distributed Lock in springcloud distributed system

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article introduces the knowledge of "how to implement distributed locks in springcloud distributed systems". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

I. brief introduction

Generally speaking, when locking the data, the program first acquires the lock through acquire to exclusive access to the data, then performs some column operations on the data, and finally needs to release the lock. Redis itself adds a lock with the watch command, which is an optimistic lock. Using the watch command can cause performance problems for frequently accessed keys.

2. Introduction of redis command

SETNX command (SET if Not eXists)

If and only if key does not exist, set the value of key to value and return 1; if the given key already exists, SETNX does not take any action and returns 0.

SETEX command

Set the timeout

GET command

Returns the string value associated with key, or the special value nil if key does not exist.

DEL command

Delete one or more given key, and key that does not exist will be ignored.

Third, the realization train of thought

Because the redis setnx command is inherently suitable for locking, this command sets the value for the key only if the key does not exist. After acquiring the lock, other programs will fail to set the value, that is, the lock will not be acquired. Failed to acquire lock. Just keep trying to acquire the lock until the lock is successfully acquired, or until the timeout is set.

In addition, in order to prevent deadlock, that is, after a program acquires the lock, the program goes wrong and is not released, and other programs are unable to acquire the lock, which leads to a series of problems and even leads to the normal operation of the system. At this point, you need to set a timeout for the lock, that is, the setex command, after the lock timeout, so that other programs can acquire the lock.

Fourth, coding implementation

This article uses springboot combined with redis to implement, so you need to install a redis.

First, the creation of springboot project is introduced, and redis is introduced.

Org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-data-redis

two。 Create a lock class

/ * Global lock, including lock name * Created by fangzhipeng on 2017-4-1. * / public class Lock {private String name; private String value; public Lock (String name, String value) {this.name = name; this.value = value;} public String getName () {return name;} public String getValue () {return value;}}

3. The specific method of creating distributed locks has been explained clearly, and the code comments have been written, so they will not be explained.

Import org.apache.commons.lang.StringUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.StringRedisTemplate;import org.springframework.data.redis.core.ValueOperations;import org.springframework.stereotype.Component;import java.util.concurrent.TimeUnit;/** * Created by fangzhipeng on 2017-4-1. * / @ Componentpublic class DistributedLockHandler {private static final Logger logger = LoggerFactory.getLogger (DistributedLockHandler.class) Private final static long LOCK_EXPIRE = 30 * 1000L 30ms / lock holding time for a single business is 30s, prevent deadlock private final static long LOCK_TRY_INTERVAL = 30L bank / default 30ms try once private final static long LOCK_TRY_TIMEOUT = 20 * 1000L hand hand / default attempt 20s @ Autowired private StringRedisTemplate template / * attempt to acquire global lock * * @ param lock lock name * @ return true obtained successfully, false acquisition failed * / public boolean tryLock (Lock lock) {return getLock (lock, LOCK_TRY_TIMEOUT, LOCK_TRY_INTERVAL, LOCK_EXPIRE) } / * attempted to acquire global lock * * @ param lock lock name * @ param timeout to obtain timeout unit ms * @ return true successfully, false acquisition failed * / public boolean tryLock (Lock lock, long timeout) {return getLock (lock, timeout, LOCK_TRY_INTERVAL, LOCK_EXPIRE) } / * try to get the name of the global lock * @ param lock lock * @ param timeout get the timeout of the lock * @ param tryInterval how many milliseconds try to get * @ return true successfully Failed to obtain false * / public boolean tryLock (Lock lock, long timeout, long tryInterval) {return getLock (lock, timeout, tryInterval, LOCK_EXPIRE) } / * try to get the name of the global lock * @ param lock lock * @ param timeout get the timeout of the lock * @ param tryInterval how many milliseconds try to get the expiration of the * @ param lockExpireTime lock * @ return true successfully Failed to obtain false * / public boolean tryLock (Lock lock, long timeout, long tryInterval, long lockExpireTime) {return getLock (lock, timeout, tryInterval, lockExpireTime) } / * Operation redis to obtain the name of the global lock * * @ param lock lock * @ param timeout timeout obtained * @ param tryInterval how many ms attempts * @ param lockExpireTime to obtain the expiration time of the lock after success * @ return true Failed to obtain false * / public boolean getLock (Lock lock, long timeout, long tryInterval, long lockExpireTime) {try {if (StringUtils.isEmpty (lock.getName ()) | | StringUtils.isEmpty (lock.getValue () {return false } long startTime = System.currentTimeMillis (); do {if (! template.hasKey (lock.getName () {ValueOperations ops = template.opsForValue (); ops.set (lock.getName (), lock.getValue (), lockExpireTime, TimeUnit.MILLISECONDS); return true } else {/ / there is a lock logger.debug ("lock is locks exist!") ;} if (System.currentTimeMillis ()-startTime > timeout) {/ / try to jump out of the loop return false;} Thread.sleep (tryInterval) directly after exceeding the set value;} while (template.hasKey (lock.getName () } catch (InterruptedException e) {logger.error (e.getMessage ()); return false;} return false;} / * release lock * / public void releaseLock (Lock lock) {if (! StringUtils.isEmpty (lock.getName () {template.delete (lock.getName ());}

4. Usage:

@ AutowiredDistributedLockHandler distributedLockHandler;Lock lock=new Lock ("lockk", "sssssssss); if (distributedLockHandler.tryLock (lock) {doSomething (); distributedLockHandler.releaseLock ();} V)

In order to prevent deadlock from using setex command when using global lock, this command needs to set the timeout of the lock according to the specific business. The other is the granularity of the lock. For example, in the actual combat of redis, there is a case, in order to achieve the function of trading market, the entire trading market is locked, resulting in insufficient performance, the improvement program only locks the goods bought and sold rather than the whole market.

This is the end of the content of "how to implement distributed locks in springcloud distributed systems". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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

Development

Wechat

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

12
Report