springcloud如何用Redlock實(shí)現(xiàn)分布式鎖
之前寫過一篇文章《如何在springcloud分布式系統(tǒng)中實(shí)現(xiàn)分布式鎖? 》,由于自己僅僅是閱讀了相關(guān)的書籍,和查閱了相關(guān)的資料,就認(rèn)為那樣的是可行的。那篇文章實(shí)現(xiàn)的大概思路是用setNx命令和setEx配合使用。 setNx是一個(gè)耗時(shí)操作,因?yàn)樗枰樵冞@個(gè)鍵是否存在,就算redis的百萬的qps,在高并發(fā)的場景下,這種操作也是有問題的。關(guān)于redis實(shí)現(xiàn)分布式鎖,redis官方推薦使用redlock。
一、redlock簡介
在不同進(jìn)程需要互斥地訪問共享資源時(shí),分布式鎖是一種非常有用的技術(shù)手段。實(shí)現(xiàn)高效的分布式鎖有三個(gè)屬性需要考慮:
安全屬性:互斥,不管什么時(shí)候,只有一個(gè)客戶端持有鎖
效率屬性A:不會死鎖
效率屬性B:容錯(cuò),只要大多數(shù)redis節(jié)點(diǎn)能夠正常工作,客戶端端都能獲取和釋放鎖。
Redlock是redis官方提出的實(shí)現(xiàn)分布式鎖管理器的算法。這個(gè)算法會比一般的普通方法更加安全可靠。關(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();
}
}
測試類:
@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
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)文章
Java數(shù)據(jù)結(jié)構(gòu)之常見排序算法(上)
這篇文章主要介紹了Java數(shù)據(jù)結(jié)構(gòu)之常見排序算法,本文章是匯總篇,且對每個(gè)排序都進(jìn)行了說明,可以很好的理清思路,對排序算法有個(gè)總體的框架,需要的朋友可以參考下2023-01-01
基于Spring Boot的Environment源碼理解實(shí)現(xiàn)分散配置詳解
這篇文章主要給大家介紹了基于Spring Boot的Environment源碼理解實(shí)現(xiàn)分散配置的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-08-08
Java中的Opencv簡介與開發(fā)環(huán)境部署方法
OpenCV是一個(gè)開源的計(jì)算機(jī)視覺和圖像處理庫,提供了豐富的圖像處理算法和工具,它支持多種圖像處理和計(jì)算機(jī)視覺算法,可以用于物體識別與跟蹤、圖像分割與邊緣檢測、圖像特征提取與描述等應(yīng)用,本文介紹Java中的Opencv簡介與開發(fā)環(huán)境部署方法,感興趣的朋友一起看看吧2025-01-01
全網(wǎng)最精細(xì)詳解二叉樹,2萬字帶你進(jìn)入算法領(lǐng)域
大家好,我是哪吒,一個(gè)熱愛編碼的Java工程師,本著"欲速則不達(dá),欲達(dá)則欲速"的學(xué)習(xí)態(tài)度,在程序猿這條不歸路上不斷成長,所謂成長,不過是用時(shí)間慢慢擦亮你的眼睛,少時(shí)看重的,年長后卻視若鴻毛,少時(shí)看輕的,年長后卻視若泰山,成長之路,亦是漸漸放下執(zhí)念,內(nèi)心歸于平靜的旅程2021-08-08
Java實(shí)現(xiàn)字符數(shù)組全排列的方法
這篇文章主要介紹了Java實(shí)現(xiàn)字符數(shù)組全排列的方法,涉及Java針對字符數(shù)組的遍歷及排序算法的實(shí)現(xiàn)技巧,需要的朋友可以參考下2015-12-12
SpringBoot使用MockMvc測試get和post接口的示例代碼
Spring Boot MockMvc是一個(gè)用于單元測試的模塊,它是Spring框架的一部分,專注于簡化Web應(yīng)用程序的測試,MockMvc主要用來模擬一個(gè)完整的HTTP請求-響應(yīng)生命周期,本文給大家介紹了SpringBoot使用MockMvc測試get和post接口,需要的朋友可以參考下2024-06-06
SpringBoot集成Kafka的實(shí)現(xiàn)示例
本文主要介紹了SpringBoot集成Kafka的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-01-01

