91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Javas使用Redlock實現分布式鎖過程解析

發布時間:2020-10-21 09:18:36 來源:腳本之家 閱讀:188 作者:方志朋 欄目:編程語言

一、redlock簡介

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

  • 安全屬性:互斥,不管什么時候,只有一個客戶端持有鎖
  • 效率屬性A:不會死鎖
  • 效率屬性B:容錯,只要大多數redis節點能夠正常工作,客戶端端都能獲取和釋放鎖。

Redlock是redis官方提出的實現分布式鎖管理器的算法。這個算法會比一般的普通方法更加安全可靠。關于這個算法的討論可以看下官方文檔。

二、怎么用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 處理完具體的業務邏輯要返回的數據
   * @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 類,實現了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();
    }
  }

運行測試類:

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

從運行結果上看,在異步任務的情況下,確實是獲取鎖之后才能運行線程。不管怎么樣,這是redis官方推薦的一種方案,可靠性比較高。有什么問題歡迎留言。

三、參考資料

https://github.com/redisson/redisson

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

甘谷县| 丹寨县| 蒙阴县| 乌审旗| 阳江市| 日照市| 孟连| 获嘉县| 晋城| 遂川县| 平果县| 宝坻区| 治县。| 稷山县| 盱眙县| 瑞昌市| 明溪县| 云安县| 云阳县| 高要市| 武定县| 东莞市| 怀宁县| 阳曲县| 台中县| 万宁市| 横峰县| 务川| 卫辉市| 岳西县| 息烽县| 九台市| 津南区| 奉新县| 林芝县| 时尚| 尼玛县| 平顶山市| 台山市| 荔波县| 长白|