欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

springcloud如何用Redlock實(shí)現(xiàn)分布式鎖

 更新時間:2021年11月10日 11:59:28   作者:方志朋  
本文主要介紹了springcloud如何用Redlock實(shí)現(xiàn)分布式鎖,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下

之前寫過一篇文章《如何在springcloud分布式系統(tǒng)中實(shí)現(xiàn)分布式鎖? 》,由于自己僅僅是閱讀了相關(guān)的書籍,和查閱了相關(guān)的資料,就認(rèn)為那樣的是可行的。那篇文章實(shí)現(xiàn)的大概思路是用setNx命令和setEx配合使用。 setNx是一個耗時操作,因?yàn)樗枰樵冞@個鍵是否存在,就算redis的百萬的qps,在高并發(fā)的場景下,這種操作也是有問題的。關(guān)于redis實(shí)現(xiàn)分布式鎖,redis官方推薦使用redlock。

一、redlock簡介

在不同進(jìn)程需要互斥地訪問共享資源時,分布式鎖是一種非常有用的技術(shù)手段。實(shí)現(xiàn)高效的分布式鎖有三個屬性需要考慮:

安全屬性:互斥,不管什么時候,只有一個客戶端持有鎖
效率屬性A:不會死鎖
效率屬性B:容錯,只要大多數(shù)redis節(jié)點(diǎn)能夠正常工作,客戶端端都能獲取和釋放鎖。
Redlock是redis官方提出的實(shí)現(xiàn)分布式鎖管理器的算法。這個算法會比一般的普通方法更加安全可靠。關(guān)于這個算法的討論可以看下官方文檔。

二、怎么用java使用 redlock

在pom文件引入redis和redisson依賴:

<!-- redis-->
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
  </dependency>
  <!-- redisson-->
  <dependency>
   <groupId>org.redisson</groupId>
   <artifactId>redisson</artifactId>
   <version>3.3.2</version>
  </dependency>

AquiredLockWorker接口類,,主要是用于獲取鎖后需要處理的邏輯:

/**
 * Created by fangzhipeng on 2017/4/5.
 * 獲取鎖后需要處理的邏輯
 */
public interface AquiredLockWorker<T> {
     T invokeAfterLockAquire() throws Exception;
}

DistributedLocker 獲取鎖管理類:

/**
 * Created by fangzhipeng on 2017/4/5.
 * 獲取鎖管理類
 */
public interface DistributedLocker {

     /**
      * 獲取鎖
      * @param resourceName  鎖的名稱
      * @param worker 獲取鎖后的處理類
      * @param <T>
      * @return 處理完具體的業(yè)務(wù)邏輯要返回的數(shù)據(jù)
      * @throws UnableToAquireLockException
      * @throws Exception
      */
     <T> T lock(String resourceName, AquiredLockWorker<T> worker) throws UnableToAquireLockException, Exception;

     <T> T lock(String resourceName, AquiredLockWorker<T> worker, int lockTime) throws UnableToAquireLockException, Exception;

}

UnableToAquireLockException ,不能獲取鎖的異常類:

/**
 * Created by fangzhipeng on 2017/4/5.
 * 異常類
 */
public class UnableToAquireLockException extends RuntimeException {

    public UnableToAquireLockException() {
    }

    public UnableToAquireLockException(String message) {
        super(message);
    }

    public UnableToAquireLockException(String message, Throwable cause) {
        super(message, cause);
    }
}

 RedissonConnector 連接類:

/**
 * Created by fangzhipeng on 2017/4/5.
 * 獲取RedissonClient連接類
 */
@Component
public class RedissonConnector {
    RedissonClient redisson;
    @PostConstruct
    public void init(){
        redisson = Redisson.create();
    }

    public RedissonClient getClient(){
        return redisson;
    }
}

RedisLocker 類,實(shí)現(xiàn)了DistributedLocker:

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;

/**
 * Created by fangzhipeng on 2017/4/5.
 */
@Component
public class RedisLocker  implements DistributedLocker{

    private final static String LOCKER_PREFIX = "lock:";

    @Autowired
    RedissonConnector redissonConnector;
    @Override
    public <T> T lock(String resourceName, AquiredLockWorker<T> worker) throws InterruptedException, UnableToAquireLockException, Exception {

        return lock(resourceName, worker, 100);
    }

    @Override
    public <T> T lock(String resourceName, AquiredLockWorker<T> worker, int lockTime) throws UnableToAquireLockException, Exception {
        RedissonClient redisson= redissonConnector.getClient();
        RLock lock = redisson.getLock(LOCKER_PREFIX + resourceName);
      // Wait for 100 seconds seconds and automatically unlock it after lockTime seconds
        boolean success = lock.tryLock(100, lockTime, TimeUnit.SECONDS);
        if (success) {
            try {
                return worker.invokeAfterLockAquire();
            } finally {
                lock.unlock();
            }
        }
        throw new UnableToAquireLockException();
    }
}

測試類:

  @Autowired
    RedisLocker distributedLocker;
    @RequestMapping(value = "/redlock")
    public String testRedlock() throws Exception{

        CountDownLatch startSignal = new CountDownLatch(1);
        CountDownLatch doneSignal = new CountDownLatch(5);
        for (int i = 0; i < 5; ++i) { // create and start threads
            new Thread(new Worker(startSignal, doneSignal)).start();
        }
        startSignal.countDown(); // let all threads proceed
        doneSignal.await();
        System.out.println("All processors done. Shutdown connection");
        return "redlock";
    }

     class Worker implements Runnable {
        private final CountDownLatch startSignal;
        private final CountDownLatch doneSignal;

        Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
            this.startSignal = startSignal;
            this.doneSignal = doneSignal;
        }

        public void run() {
            try {
                startSignal.await();
                distributedLocker.lock("test",new AquiredLockWorker<Object>() {

                    @Override
                    public Object invokeAfterLockAquire() {
                        doTask();
                        return null;
                    }

                });
            }catch (Exception e){

            }
        }

        void doTask() {
            System.out.println(Thread.currentThread().getName() + " start");
            Random random = new Random();
            int _int = random.nextInt(200);
            System.out.println(Thread.currentThread().getName() + " sleep " + _int + "millis");
            try {
                Thread.sleep(_int);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " end");
            doneSignal.countDown();
        }
    }

運(yùn)行測試類:

Thread-48 start
Thread-48 sleep 99millis
Thread-48 end
Thread-49 start
Thread-49 sleep 118millis
Thread-49 end
Thread-52 start
Thread-52 sleep 141millis
Thread-52 end
Thread-50 start
Thread-50 sleep 28millis
Thread-50 end
Thread-51 start
Thread-51 sleep 145millis
Thread-51 end

從運(yùn)行結(jié)果上看,在異步任務(wù)的情況下,確實(shí)是獲取鎖之后才能運(yùn)行線程。不管怎么樣,這是redis官方推薦的一種方案,可靠性比較高。

三、參考資料

https://github.com/redisson/redisson

《Redis官方文檔》用Redis構(gòu)建分布式鎖

A Look at the Java Distributed In-Memory Data Model (Powered by Redis)

到此這篇關(guān)于springcloud如何用Redlock實(shí)現(xiàn)分布式鎖的文章就介紹到這了,更多相關(guān)springcloud Redlock分布式鎖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringMVC的組件之HandlerExceptionResolver詳解

    SpringMVC的組件之HandlerExceptionResolver詳解

    這篇文章主要介紹了SpringMVC的組件之HandlerExceptionResolver詳解,不管是在處理請求映射(HandlerMapping),還是在請求被處理(Handler)時拋出的異常,DispatcherServlet都會委托給HandlerExceptionResolver進(jìn)行異常處理,該接口只有一個方法,需要的朋友可以參考下
    2023-10-10
  • SpringBoot2.x設(shè)置Session失效時間及失效跳轉(zhuǎn)方式

    SpringBoot2.x設(shè)置Session失效時間及失效跳轉(zhuǎn)方式

    這篇文章主要介紹了SpringBoot2.x設(shè)置Session失效時間及失效跳轉(zhuǎn)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • java中線程的狀態(tài)學(xué)習(xí)筆記

    java中線程的狀態(tài)學(xué)習(xí)筆記

    在本文里我們給大家整理了關(guān)于java中線程的狀態(tài)的相關(guān)知識點(diǎn)內(nèi)容,對此有需要的朋友們學(xué)習(xí)參考下。
    2019-03-03
  • 玩轉(zhuǎn)spring boot 結(jié)合AngularJs和JDBC(4)

    玩轉(zhuǎn)spring boot 結(jié)合AngularJs和JDBC(4)

    玩轉(zhuǎn)spring boot,這篇文章主要介紹了結(jié)合AngularJs和JDBC,玩轉(zhuǎn)spring boot,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-01-01
  • Apache?log4j2-RCE?漏洞復(fù)現(xiàn)及修復(fù)建議(CVE-2021-44228)

    Apache?log4j2-RCE?漏洞復(fù)現(xiàn)及修復(fù)建議(CVE-2021-44228)

    Apache?Log4j2是一款Java日志框架,大量應(yīng)用于業(yè)務(wù)系統(tǒng)開發(fā)。2021年11月24日,阿里云安全團(tuán)隊向Apache官方報告了Apache?Log4j2遠(yuǎn)程代碼執(zhí)行漏洞(CVE-2021-44228),本文給大家介紹Apache?log4j2-RCE?漏洞復(fù)現(xiàn)(CVE-2021-44228)的相關(guān)知識,感興趣的朋友一起看看吧
    2021-12-12
  • Java的Character類詳解

    Java的Character類詳解

    在實(shí)際開發(fā)過程中,我們經(jīng)常會遇到需要使用對象,而不是內(nèi)置數(shù)據(jù)類型的情況。為了解決這個問題,Java語言為內(nèi)置數(shù)據(jù)類型char提供了包裝類Character類。本文詳細(xì)介紹了Java的Character類,感興趣的同學(xué)可以參考閱讀
    2023-04-04
  • SpringCloud用Zookeeper搭建配置中心的方法

    SpringCloud用Zookeeper搭建配置中心的方法

    本篇文章主要介紹了SpringCloud用Zookeeper搭建配置中心的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-04-04
  • java文件讀寫操作實(shí)例詳解

    java文件讀寫操作實(shí)例詳解

    java的io流讀取數(shù)據(jù)使用io流讀取文件和向文件中寫數(shù)據(jù),這篇文章主要給大家介紹了關(guān)于java文件讀寫操作的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-02-02
  • Java異常處理try?catch的基本用法

    Java異常處理try?catch的基本用法

    try就像一個網(wǎng),把try{}里面的代碼所拋出的異常都網(wǎng)住,然后把異常交給catch{}里面的代碼去處理。最后執(zhí)行finally之中的代碼。無論try中代碼有沒有異常,也無論catch是否將異常捕獲到,finally中的代碼都一定會被執(zhí)行。
    2021-12-12
  • Java基礎(chǔ)入門篇之邏輯控制練習(xí)題與猜數(shù)字游戲

    Java基礎(chǔ)入門篇之邏輯控制練習(xí)題與猜數(shù)字游戲

    猜數(shù)字游戲是一款經(jīng)典的游戲,該游戲說簡單也很簡單,說不簡單確實(shí)也很難,這篇文章主要給大家介紹了關(guān)于Java基礎(chǔ)入門篇之邏輯控制練習(xí)題與猜數(shù)字游戲的相關(guān)資料,需要的朋友可以參考下
    2023-06-06

最新評論