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 use consul to realize distributed Lock scenario in spring boot

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

Share

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

This article introduces the knowledge of "how to use consul to implement distributed locking scenarios in spring boot". In the operation of actual cases, many people will encounter such a dilemma, 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!

The following is the lock implementation code:

Package com.lyb.consullock;import com.ecwid.consul.v1.ConsulClient;import com.ecwid.consul.v1.agent.model.NewCheck;import com.ecwid.consul.v1.kv.model.PutParams;import com.ecwid.consul.v1.session.model.NewSession;import com.ecwid.consul.v1.session.model.Session;import lombok.Data;import java.time.LocalDateTime;import java.util.ArrayList;import java.util.List;public class DistributedLock {private ConsulClient consulClient / * * Constructor * @ param consulHost registers the client of consul or the Ip or hostname of the server, or the domain name * @ param consulPort port number * / public DistributedLock (String consulHost,int consulPort) {consulClient = new ConsulClient (consulHost,consulPort) } / * method for obtaining locks * @ param lockName competing resource names * @ param ttlSeconds lock timeout is automatically released * @ return * / public LockContext getLock (String lockName,int ttlSeconds) {LockContext lockContext = new LockContext (); if (ttlSeconds 86400) ttlSeconds = 60; String sessionId = createSession (lockName,ttlSeconds) Boolean success = lock (lockName,sessionId); if (success = = false) {consulClient.sessionDestroy (sessionId,null); lockContext.setGetLock (false); return lockContext;} lockContext.setSession (sessionId); lockContext.setGetLock (true); return lockContext } / * release lock * @ param sessionID * / public void releaseLock (String sessionID) {consulClient.sessionDestroy (sessionID,null);} private String createSession (String lockName,int ttlSeconds) {NewCheck check = new NewCheck (); check.setId ("check" + lockName); check.setName (check.getId ()); check.setTtl (ttlSeconds+ "s") / / this value and session ttl jointly determine the lock duration check.setTimeout ("10s"); consulClient.agentCheckRegister (check); consulClient.agentCheckPass (check.getId ()); NewSession session = new NewSession (); session.setBehavior (Session.Behavior.RELEASE); session.setName ("session" + lockName); session.setLockDelay (1); session.setTtl (ttlSeconds + "s") / / jointly determine the lock duration List checks = new ArrayList (); checks.add (check.getId ()); session.setChecks (checks); String sessionId = consulClient.sessionCreate (session,null). GetValue (); return sessionId;} private boolean lock (String lockName,String sessionId) {PutParams putParams = new PutParams (); putParams.setAcquireSession (sessionId) Boolean isSuccess = consulClient.setKVValue (lockName, "lock:" + LocalDateTime.now (), putParams). GetValue (); return isSuccess;} / * * the object returned in the event of a competitive lock * / @ Data public class LockContext {/ * * is successfully returned by the lock, and this value is later used to release the lock * / private String session. / * whether to get the lock * / private boolean isGetLock;}}

Pom file

4.0.0 org.springframework.boot spring-boot-starter-parent 2.1.6.RELEASE com.lyb consul-lock 0.0.1-SNAPSHOT consul-lock Demo project for Spring Boot 1.8 Greenwich.SR2 org.springframework.boot spring-boot-starter-web Org.springframework.cloud spring-cloud-starter-consul-discovery org.springframework.boot spring-boot-starter-actuator org.projectlombok lombok 1.18.8 true org.springframework.boot spring-boot-starter -test test org.springframework.cloud spring-cloud-dependencies ${spring-cloud.version} pom import org.springframework.boot spring-boot-maven-plugin

Test the code:

Package com.lyb.consullock;import org.junit.Assert;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;@RunWith (SpringRunner.class) @ SpringBootTestpublic class ConsulLockApplicationTests {@ Autowired private ServiceConfig serviceConfig @ Test public void lockSameResourer () {/ / for the same resource, only one thread will acquire the lock ExecutorService threadPool = Executors.newFixedThreadPool (10) at the same time; for (int axion a {for (int I = 0 I < 100) DistributedLock lock +) {DistributedLock lock = new DistributedLock (serviceConfig.getConsulRegisterHost (), serviceConfig.getConsulRegisterPort ()); DistributedLock.LockContext lockContext = lock.getLock ("test lock", 10) If (lockContext.isGetLock ()) {System.out.println (Thread.currentThread () .getName () + "acquired lock"); try {TimeUnit.SECONDS.sleep (1) Lock.releaseLock (lockContext.getSession ());} catch (InterruptedException e) {e.printStackTrace () }} else {/ / System.out.println (Thread.currentThread () .getName () + "No lock obtained");}) } try {TimeUnit.MINUTES.sleep (2);} catch (InterruptedException e) {e.printStackTrace ();}} @ Test public void lockDiffResource () {/ / all threads should be able to acquire locks ExecutorService threadPool = Executors.newFixedThreadPool (10) for unavailable resources; for (int astat0) A {for (int I = 0 * * I < 100; iTunes +) {DistributedLock lock = new DistributedLock (serviceConfig.getConsulRegisterHost (), serviceConfig.getConsulRegisterPort ()) DistributedLock.LockContext lockContext = lock.getLock ("test lock" + Thread.currentThread (). GetName (), 10); if (lockContext.isGetLock ()) {System.out.println (Thread.currentThread (). GetName () + "acquired lock") Try {TimeUnit.SECONDS.sleep (1); lock.releaseLock (lockContext.getSession ());} catch (InterruptedException e) {e.printStackTrace () }} else {/ / System.out.println (Thread.currentThread () .getName () + "No lock acquired"); Assert.assertTrue (lockContext.isGetLock ()) });} try {TimeUnit.MINUTES.sleep (2);} catch (InterruptedException e) {e.printStackTrace () This is the end of "how to use consul to implement distributed locking scenarios in spring boot". 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