maven引入Redisson使用

如果你希望在 Maven 項(xiàng)目中使用 Redisson,你需要向你的 pom.xml 文件添加以下依賴項(xiàng):

<dependency>
  <groupId>org.redisson</groupId>
  <artifactId>redisson</artifactId>
  <version>${redisson.version}</version>
</dependency>

其中 ${redisson.version} 是 Redisson 版本號(hào),可以根據(jù)你的需求進(jìn)行替換。
然后引入 Redisson 的相關(guān)類并進(jìn)行配置,我寫了一個(gè)下面的工具類:

package src.main.biz.ucenter.redis;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedissonUtils {

    private RedissonClient redissonClient;

    @Value("${spring.redis.host}")
    private String redisHost;

    @Value("${spring.redis.port}")
    private int redisPort;

    @Value("${spring.redis.password:}")
    private String redisPassword;

    /**
     * 獲取RedissonClient單例實(shí)例
     *
     * @return RedissonClient
     */
    public RedissonClient getRedissonClient() {
        if (redissonClient == null) {
            Config config = new Config();
            config.useSingleServer()
                    .setAddress("redis://" + redisHost + ":" + redisPort)
                    .setPassword(redisPassword)
                    .setDatabase(0);
            redissonClient = Redisson.create(config);
        }
        return redissonClient;
    }

    /**
     * 根據(jù)key獲取分布式鎖
     *
     * @param key 鎖的key
     * @return RLock分布式鎖對(duì)象
     */
    public RLock getLock(String key) {
        return getRedissonClient().getLock(key);
    }

    /**
     * 嘗試獲取分布式鎖,等待指定時(shí)間
     *
     * @param lock    分布式鎖對(duì)象
     * @param timeout 超時(shí)時(shí)間(單位:秒)
     * @return 是否成功獲取鎖
     * @throws InterruptedException 中斷異常
     */
    public boolean tryLock(RLock lock, long timeout) throws InterruptedException {
        return lock.tryLock(timeout, TimeUnit.SECONDS);
    }

    /**
     * 釋放分布式鎖
     *
     * @param lock 分布式鎖對(duì)象
     */
    public void unlock(RLock lock) {
        lock.unlock();
    }

}



在上面的代碼中,RedissonUtils 類對(duì) Redisson 的使用進(jìn)行了優(yōu)化和簡(jiǎn)化。取消了 getLock 方法中的超時(shí)時(shí)間參數(shù),默認(rèn)使用 Redisson 的默認(rèn)超時(shí)時(shí)間;將嘗試獲取鎖的方法單獨(dú)提取出來作為一個(gè)公共方法,以便于自定義等待時(shí)間;取消了 getRedissonClient 方法中的單例實(shí)現(xiàn),并改為直接返回 RedissonClient 實(shí)例。

同時(shí),在 tryLock 方法中,我們拋出了 InterruptedException 異常,因此在調(diào)用 tryLock 方法時(shí)需要進(jìn)行異常處理,通常是將異常向上層方法傳遞或者捕獲并處理異常。在釋放鎖時(shí),我們使用 lock.unlock() 來釋放鎖。

下面的是demo

import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import src.main.biz.ucenter.redis.RedissonUtils;

@Service
public class MyService {

    @Autowired
    private RedissonUtils redissonUtils;

    public void myMethod() {
        String lockKey = "myLock";
        RLock lock = redissonUtils.getLock(lockKey);
        try {
            boolean locked = redissonUtils.tryLock(lock, 60);
            if (locked) {
                // 獲取到鎖,執(zhí)行業(yè)務(wù)邏輯
                // ...
            } else {
                // 獲取鎖失敗,處理異常情況
                // ...
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            // 處理中斷異常
            // ...
        } finally {
            redissonUtils.unlock(lock);
        }
    }

}

在上面的代碼中,MyService 類中的 myMethod 方法使用了 Redisson 獲取分布式鎖。我們首先定義一個(gè)鎖的 key 值,然后通過 redissonUtils.getLock(lockKey) 來獲取對(duì)應(yīng)的分布式鎖對(duì)象。接著,我們調(diào)用 redissonUtils.tryLock(lock, 60) 來嘗試獲取鎖,并指定超時(shí)時(shí)間為 60 秒。如果成功獲得鎖,則可以執(zhí)行業(yè)務(wù)邏輯,否則需要處理獲取鎖失敗的異常情況。在最后,我們使用 redissonUtils.unlock(lock) 來釋放鎖。

需要注意的是,在 tryLock 方法中,我們拋出了 InterruptedException 異常,因此在調(diào)用 tryLock 方法時(shí)需要進(jìn)行異常處理,通常是將異常向上層方法傳遞或者捕獲并處理異常。

在 Redisson 中,getLock() 方法獲取鎖時(shí)默認(rèn)的等待時(shí)間是 30 秒(30,000 毫秒),可以通過 org.redisson.api.RLock#lock(long waitTime, long leaseTime, TimeUnit unit) 方法的第一個(gè)參數(shù)來指定等待時(shí)間。例如,lock.lock(10, TimeUnit.SECONDS) 將會(huì)在獲取鎖之前等待最多 10 秒鐘,如果在這個(gè)時(shí)間內(nèi)無法獲取到鎖,則會(huì)拋出 org.redisson.api.RLockTimeoutException 異常。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容