Javas使用Redlock實(shí)現(xiàn)分布式鎖過程解析
一、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
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Java基于redis實(shí)現(xiàn)分布式鎖
- 淺談Java分布式架構(gòu)下如何實(shí)現(xiàn)分布式鎖
- 通過實(shí)例解析Java分布式鎖三種實(shí)現(xiàn)方法
- Java基于redis實(shí)現(xiàn)分布式鎖代碼實(shí)例
- Java redisson實(shí)現(xiàn)分布式鎖原理詳解
- Java注解如何基于Redission實(shí)現(xiàn)分布式鎖
- Java Redis分布式鎖的正確實(shí)現(xiàn)方式詳解
- 淺談Java(SpringBoot)基于zookeeper的分布式鎖實(shí)現(xiàn)
- 深入淺出探索Java分布式鎖原理
相關(guān)文章
spring+springmvc整合mabytis時mapper注入失敗問題解決方法
這篇文章主要介紹了spring+springmvc整合mabytis時mapper注入失敗問題解決方法 ,需要的朋友可以參考下2017-08-08
Spring?Data?Elasticsearch使用方式(Elasticsearch)
這篇文章主要介紹了Spring?Data?Elasticsearch使用方式(Elasticsearch),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-04-04
Spring Boot項(xiàng)目中結(jié)合MyBatis實(shí)現(xiàn)MySQL的自動主從切換功能
這篇文章主要介紹了Spring Boot項(xiàng)目中結(jié)合MyBatis實(shí)現(xiàn)MySQL的自動主從切換功能,本文分步驟給大家介紹的非常詳細(xì),感興趣的朋友一起看看吧2025-04-04
Java錯誤:進(jìn)行語法分析時已到達(dá)文件結(jié)尾的解決
這篇文章主要介紹了Java錯誤:進(jìn)行語法分析時已到達(dá)文件結(jié)尾的解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-08-08
Spring IOC和DI實(shí)現(xiàn)原理及實(shí)例解析
這篇文章主要介紹了Spring IOC和DI實(shí)現(xiàn)原理及實(shí)例解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-06-06
Windows同時安裝兩個版本JDK并實(shí)現(xiàn)動態(tài)切換JAVA8或JAVA11的方法
這篇文章主要給大家介紹了關(guān)于Windows同時安裝兩個版本JDK并實(shí)現(xiàn)動態(tài)切換JAVA8或JAVA11的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2022-11-11

