Javas使用Redlock實(shí)現(xiàn)分布式鎖過(guò)程解析
一、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í)有所幫助,也希望大家多多支持腳本之家。
- Java基于redis實(shí)現(xiàn)分布式鎖
- 淺談Java分布式架構(gòu)下如何實(shí)現(xiàn)分布式鎖
- 通過(guò)實(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)文章
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-08SpringBoot如何整合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è)計(jì)模式編程中單例模式的使用
這篇文章主要介紹了深入解析Java的設(shè)計(jì)模式編程中單例模式的使用,一般來(lái)說(shuō)將單例模式分為餓漢式單例和懶漢式單例,需要的朋友可以參考下2016-02-02java 非對(duì)稱加密算法RSA實(shí)現(xiàn)詳解
這篇文章主要介紹了java 非對(duì)稱加密算法RSA實(shí)現(xiàn)詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-07-07java 實(shí)現(xiàn)回調(diào)代碼實(shí)例
本文主要介紹Java的回調(diào)機(jī)制,并附實(shí)例代碼以供大家參考學(xué)習(xí),有需要的小伙伴可以看下2016-07-07深入理解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