Redisson分布式锁实战-1:构建分布式锁
生活随笔
收集整理的這篇文章主要介紹了
Redisson分布式锁实战-1:构建分布式锁
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
我們現在來到Task類當中,這個方法就是V4了/*** Redisson分布式鎖實現* @throws InterruptedException*/
// @Scheduled(cron="0 */1 * * * ?")//每1分鐘(每個1分鐘的整數倍)public void closeOrderTaskV4() throws InterruptedException {RLock lock = redissonManager.getRedisson().getLock(Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK);boolean getLock = false;try {if(getLock = lock.tryLock(2,50, TimeUnit.SECONDS)){//trylock增加鎖log.info("===獲取{},ThreadName:{}",Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK,Thread.currentThread().getName());int hour = Integer.parseInt(PropertiesUtil.getProperty("close.order.task.time.hour","2"));iOrderService.closeOrder(hour);}else{log.info("===沒有獲得分布式鎖:{}",Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK);}}finally {if(!getLock){return;}log.info("===釋放分布式鎖:{}",Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK);lock.unlock();}}V4我們就要用Redisson來搞定分布式鎖,其實我們原生實現的單點登陸,使用Spring Session實現單點登陸,原先我們實現的分布式鎖,然后使用Redisson分布式鎖都是這么一個過程,先原生實現,然后調用框架實現,本身我們原生實現完之后,基礎會更扎實,然后再學習一些簡單的框架呢,也會更快,例如Spring Session侵入性會比較小,那在改造的時候呢,在單位推動這個框架也更容易一些,使用Redisson來實現這個分布式鎖,首先要把之前聲明的RedissonManager注入到我們這個類當中,@Autowiredprivate RedissonManager redissonManager;然后直接使用他,首先聲明一個RLock,Redisson的一個lock,我們先獲取到Redisson這個實例,我們點tryLock,tryLock是嘗試獲取鎖,也就是我們原來V3講的版本,這里面嘗試獲取鎖,把這些都封裝好了,第一個有參數可以添加等待時間,鎖的自動解鎖時間,還有時間的一個單位,首先waittime是什么,嘗試獲取鎖的時候,我最多等待兩秒,那多久釋放呢,5秒釋放,也就是說這個鎖最多放5秒,然后最后寫上單位,tryLock的返回值是一個布爾/*** Returns <code>true</code> as soon as the lock is acquired.* If the lock is currently held by another thread in this or any* other process in the distributed system this method keeps trying* to acquire the lock for up to <code>waitTime</code> before* giving up and returning <code>false</code>. If the lock is acquired,* it is held until <code>unlock</code> is invoked, or until <code>leaseTime</code>* have passed since the lock was granted - whichever comes first.** @param waitTime the maximum time to aquire the lock* @param leaseTime lease time* @param unit time unit* @return <code>true</code> if lock has been successfully acquired* @throws InterruptedException - if the thread is interrupted before or during this method.*/boolean tryLock(long waitTime, long leaseTime, TimeUnit unit) throws InterruptedException;那返回值代表是否獲取鎖成功,我們在上面給一個默認值,getLock是否獲取到鎖,默認是false,然后這里面要做一個判斷,那座判斷的時候還要給他更新,獲取鎖并把返回值賦給getLock,如果為true的話就會進入到if里邊,我們打印一個日志,Redisson獲取分布式鎖,線程的名字,鎖的名字,然后還要獲取我們的小時,這里面我們就不調用closeOrder了,我們把分布式鎖都交給Redisson來管理了,所以我們這里封裝的,包括時間的控制,我們都不需要操作了,我們只把這個時間拿過來,然后可以直接調用iOrderService.closeOrder(hour),那這個Catch是一個打斷的Exception,那這個Catch我們也要打一個日志,Redisson鎖獲取異常,這里面需要注意一下,我們要把finally加上,提高一下我們的代碼健壯性,如果getLock沒有拿到的話,直接返回,所以我們在finally里面調用unlock來釋放這個鎖,也就是說,鎖用完之后,finally是肯定要執行的,然后在這里面要釋放這個鎖了,然后打印一個日志,Redisson分布式鎖釋放鎖,finally一定不要忘記加,提高了我們代碼的一個健壯性,我在tryLock的時候只等一秒,沒有的時候就走人了
?
超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生總結
以上是生活随笔為你收集整理的Redisson分布式锁实战-1:构建分布式锁的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Redisson初始化
- 下一篇: Redisson分布式锁实战-2:解决w