溫馨提示×

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

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何正確的使用redisson分布式鎖

發(fā)布時(shí)間:2021-03-18 15:06:36 來(lái)源:億速云 閱讀:349 作者:Leah 欄目:開發(fā)技術(shù)

這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)?lái)有關(guān)如何正確的使用redisson分布式鎖,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

Redisson是Redis官方推薦的Java版的Redis客戶端。它提供的功能非常多,此處我們只用它的分布式鎖功能。

以springboot整合Redisson項(xiàng)目為例

添加springboot maven依賴

<dependency>
	<groupId>org.redisson</groupId>
  <artifactId>redisson-spring-boot-starter</artifactId>
  <version>3.15.1</version>
</dependency>

配置 redisson就不細(xì)講了,咱們這邊用默認(rèn)配置,什么都不用配
編寫測(cè)試代碼

package com.miyou;

import org.junit.jupiter.api.Test;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.locks.Lock;

public class DefaultTest extends UserRightsApplicationTests {


  @Autowired
  private RedissonClient redissonClient;

  @Test
  public void testLock() throws InterruptedException {
    Lock lock = redissonClient.getLock("test lock");
    lock.lock();
    System.out.println("鎖獲取成功");
    new Thread(()->{
      Lock rLock2 = redissonClient.getLock("test lock");
      rLock2.lock();
      System.out.println("線程2獲取鎖成功!");
      rLock2.unlock();
    }).start();
    Thread.sleep(20000);
    System.out.println("主線程釋放鎖");
    lock.unlock();
    Thread.sleep(1200000);
  }
}

默認(rèn)情況下redisson分布式鎖的超時(shí)時(shí)間為30秒,在鎖即將超時(shí)的情況下redisson會(huì)檢查拿到鎖的線程id是否存活,如果線程存活redisson會(huì)對(duì)超時(shí)時(shí)間進(jìn)行續(xù)期

redissonClient.getLock方法返回的接口類型為
org.redisson.api.RLock
查看源碼,可以看到RLock繼承了java.util.concurrent.locks.Lock接口

如何正確的使用redisson分布式鎖

可以無(wú)縫對(duì)接使用Lock的業(yè)務(wù)場(chǎng)景,實(shí)現(xiàn)設(shè)計(jì)和傳遞

上述就是小編為大家分享的如何正確的使用redisson分布式鎖了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI