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

Javas使用Redlock實(shí)現(xiàn)分布式鎖過(guò)程解析

 更新時(shí)間:2019年08月22日 09:39:18   作者:方志朋  
這篇文章主要介紹了Javas使用Redlock實(shí)現(xiàn)分布式鎖過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

一、redlock簡(jiǎn)介

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

  • 安全屬性:互斥,不管什么時(shí)候,只有一個(gè)客戶端持有鎖
  • 效率屬性A:不會(huì)死鎖
  • 效率屬性B:容錯(cuò),只要大多數(shù)redis節(jié)點(diǎn)能夠正常工作,客戶端端都能獲取和釋放鎖。

Redlock是redis官方提出的實(shí)現(xiàn)分布式鎖管理器的算法。這個(gè)算法會(huì)比一般的普通方法更加安全可靠。關(guān)于這個(gè)算法的討論可以看下官方文檔。

二、怎么用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();
  }
}

測(cè)試類:

 @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)行測(cè)試類:

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官方推薦的一種方案,可靠性比較高。有什么問(wèn)題歡迎留言。

三、參考資料

https://github.com/redisson/redisson

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • SpringCache結(jié)合Redis實(shí)現(xiàn)指定過(guò)期時(shí)間和到期自動(dòng)刷新

    SpringCache結(jié)合Redis實(shí)現(xiàn)指定過(guò)期時(shí)間和到期自動(dòng)刷新

    本文主要介紹了SpringCache結(jié)合Redis實(shí)現(xiàn)指定過(guò)期時(shí)間和到期自動(dòng)刷新,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2024-08-08
  • 一文深入了解Java中的AtomicInteger類

    一文深入了解Java中的AtomicInteger類

    AtomicInteger是java并發(fā)包下面提供的原子類,主要操作的是int類型的整型,通過(guò)調(diào)用底層Unsafe的CAS等方法實(shí)現(xiàn)原子操作,這篇文章主要給大家介紹了關(guān)于如何通過(guò)一文深入了解Java中AtomicInteger類的相關(guān)資料,需要的朋友可以參考下
    2024-02-02
  • SpringBoot如何整合mybatis-generator-maven-plugin 1.4.0

    SpringBoot如何整合mybatis-generator-maven-plugin 1.4.0

    這篇文章主要介紹了SpringBoot整合mybatis-generator-maven-plugin 1.4.0的實(shí)現(xiàn)方法,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2023-01-01
  • Java實(shí)現(xiàn)url加密處理的方法示例

    Java實(shí)現(xiàn)url加密處理的方法示例

    這篇文章主要介紹了Java實(shí)現(xiàn)url加密處理的方法,涉及java基于base64、編碼轉(zhuǎn)換實(shí)現(xiàn)加密解密相關(guān)操作技巧,需要的朋友可以參考下
    2017-06-06
  • 詳解Java 連接MongoDB集群的幾種方式

    詳解Java 連接MongoDB集群的幾種方式

    這篇文章主要介紹了詳解Java 連接MongoDB集群的幾種方式,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2018-12-12
  • 深入解析Java的設(shè)計(jì)模式編程中單例模式的使用

    深入解析Java的設(shè)計(jì)模式編程中單例模式的使用

    這篇文章主要介紹了深入解析Java的設(shè)計(jì)模式編程中單例模式的使用,一般來(lái)說(shuō)將單例模式分為餓漢式單例和懶漢式單例,需要的朋友可以參考下
    2016-02-02
  • java 非對(duì)稱加密算法RSA實(shí)現(xiàn)詳解

    java 非對(duì)稱加密算法RSA實(shí)現(xiàn)詳解

    這篇文章主要介紹了java 非對(duì)稱加密算法RSA實(shí)現(xiàn)詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-07-07
  • java 實(shí)現(xiàn)回調(diào)代碼實(shí)例

    java 實(shí)現(xiàn)回調(diào)代碼實(shí)例

    本文主要介紹Java的回調(diào)機(jī)制,并附實(shí)例代碼以供大家參考學(xué)習(xí),有需要的小伙伴可以看下
    2016-07-07
  • log4j2日志異步打印(實(shí)例講解)

    log4j2日志異步打印(實(shí)例講解)

    下面小編就為大家?guī)?lái)一篇log4j2日志異步打印(實(shí)例講解)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-10-10
  • 深入理解Spring注解@Async解決異步調(diào)用問(wèn)題

    深入理解Spring注解@Async解決異步調(diào)用問(wèn)題

    這篇文章主要介紹了深入理解Spring注解@Async解決異步調(diào)用問(wèn)題,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-07-07

最新評(píng)論