溫馨提示×

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

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

Redisson加鎖解鎖怎么實(shí)現(xiàn)

發(fā)布時(shí)間:2022-08-26 14:41:50 來(lái)源:億速云 閱讀:178 作者:iii 欄目:開(kāi)發(fā)技術(shù)

本篇內(nèi)容介紹了“Redisson加鎖解鎖怎么實(shí)現(xiàn)”的有關(guān)知識(shí),在實(shí)際案例的操作過(guò)程中,不少人都會(huì)遇到這樣的困境,接下來(lái)就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

分布式鎖使用

對(duì)于 redisson 分布式鎖的使用很簡(jiǎn)單:

1、調(diào)用 getLock 函數(shù)獲取鎖操作對(duì)象;
2、調(diào)用 tryLock 函數(shù)進(jìn)行加鎖;
3、調(diào)用 unlock 函數(shù)進(jìn)行解鎖;

注意 unlock 操作需要放到 finally 代碼段中,保證鎖可以被釋放。

private void sumLock() {
    lock = redissonClient.getLock("sum-lock");
    
    boolean b = lock.tryLock();
    if (!b) {
        log.info("獲取不到鎖");
        return;
    }
    
    try {
        for (int j = 0; j < 20000; j++) {
            ++sum;
        }
    } finally {
        lock.unlock();
    }
    
}

getLock

getLock 實(shí)例化 RedissonLock,相當(dāng)于 Lock lock = new ReentrantLock() 操作;

public RLock getLock(String name) {
    // 實(shí)例化 RedissonLock,參數(shù)為指令執(zhí)行器和鎖名稱(chēng)
    return new RedissonLock(this.connectionManager.getCommandExecutor(), name);
}

public RedissonLock(CommandAsyncExecutor commandExecutor, String name) {
    super(commandExecutor, name);
    // 命令執(zhí)行器,用于執(zhí)行l(wèi)ua腳本
    this.commandExecutor = commandExecutor;
    // 連接管理器的ID
    this.id = commandExecutor.getConnectionManager().getId();
    // 鎖續(xù)期時(shí)間(看門(mén)狗),鎖默認(rèn)續(xù)期時(shí)間是 30s。
    this.internalLockLeaseTime = commandExecutor.getConnectionManager().getCfg().getLockWatchdogTimeout();
    this.entryName = this.id + ":" + name;
    this.pubSub = commandExecutor.getConnectionManager().getSubscribeService().getLockPubSub();
}

tryLock

@Override
public boolean tryLock() {
    return get(tryLockAsync());
}

@Override
public RFuture<Boolean> tryLockAsync() {
    return tryLockAsync(Thread.currentThread().getId());
}

@Override
public RFuture<Boolean> tryLockAsync(long threadId) {
    return tryAcquireOnceAsync(-1, -1, null, threadId);
}

這里是一系列的調(diào)用,可以直接跳過(guò),直接進(jìn)入到 tryAcquireOnceAsync 函數(shù),看看 tryAcquireOnceAsync 函數(shù)的處理邏輯。

private RFuture<Boolean> tryAcquireOnceAsync(long waitTime, long leaseTime, TimeUnit unit, long threadId) {
    // 由于我們調(diào)用tryLocak沒(méi)有傳遞任何參數(shù),leaseTime默認(rèn)為-1,不走判斷
    if (leaseTime != -1) {
        return tryLockInnerAsync(waitTime, leaseTime, unit, threadId, RedisCommands.EVAL_NULL_BOOLEAN);
    }
    
    // 調(diào)用獲取鎖 枷鎖的主要邏輯在這里
    RFuture<Boolean> ttlRemainingFuture = tryLockInnerAsync(waitTime,
                                                commandExecutor.getConnectionManager().getCfg().getLockWatchdogTimeout(),
                                                TimeUnit.MILLISECONDS, threadId, RedisCommands.EVAL_NULL_BOOLEAN);
    
    ttlRemainingFuture.onComplete((ttlRemaining, e) -> {
        // 如果發(fā)生異常那么直接放回了
        if (e != null) {
            return;
        }

        // 鎖續(xù)期
        if (ttlRemaining) {
            scheduleExpirationRenewal(threadId);
        }
    });
    // 返回結(jié)果
    return ttlRemainingFuture;
}
<T> RFuture<T> tryLockInnerAsync(long waitTime, long leaseTime, TimeUnit unit, long threadId, RedisStrictCommand<T> command) {
    // 將時(shí)間轉(zhuǎn)化為毫秒
    internalLockLeaseTime = unit.toMillis(leaseTime);
    // 執(zhí)行腳本
    return evalWriteAsync(getName(), LongCodec.INSTANCE, command,
            "if (redis.call('exists', KEYS[1]) == 0) then " +
                    "redis.call('hincrby', KEYS[1], ARGV[2], 1); " +
                    "redis.call('pexpire', KEYS[1], ARGV[1]); " +
                    "return nil; " +
                    "end; " +
                    "if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then " +
                    "redis.call('hincrby', KEYS[1], ARGV[2], 1); " +
                    "redis.call('pexpire', KEYS[1], ARGV[1]); " +
                    "return nil; " +
                    "end; " +
                    "return redis.call('pttl', KEYS[1]);",
            Collections.singletonList(getName()), internalLockLeaseTime, getLockName(threadId));
}

Redisson 中存儲(chǔ)鎖的數(shù)據(jù)類(lèi)型結(jié)構(gòu)采用的的是 hash,Key 為鎖名稱(chēng),VALUE的屬性是 Redisson 客戶(hù)端ID和線程ID組合而成的字符串,值是鎖的重入次數(shù),采用 hash 計(jì)數(shù)實(shí)現(xiàn)鎖的重入性。

Redisson加鎖解鎖怎么實(shí)現(xiàn)

該函數(shù)主要執(zhí)行 lua 腳本,腳本的邏輯為:

1、redis.call(&lsquo;exists&rsquo;, KEYS[1]) == 0 用于判斷鎖是否存在,等于 0 說(shuō)明不存在,表明此時(shí)沒(méi)有客戶(hù)端持有鎖,此客戶(hù)端獲取鎖成功;走步驟 2,否則走步驟 4;
2、設(shè)置鎖,并且對(duì)鎖進(jìn)行 +1 操作,標(biāo)識(shí)獲取鎖的次數(shù);
3、為鎖設(shè)置過(guò)期時(shí)間,成功返回 nil;
4、redis.call(&lsquo;hexists&rsquo;, KEYS[1], ARGV[2]) == 1 判斷鎖是否本客戶(hù)端持有,等于1說(shuō)明是,此時(shí)是再次獲取鎖(重入),走步驟 5,否則走 7;
5、對(duì)鎖進(jìn)行 +1 操作,標(biāo)識(shí)獲取鎖的次數(shù);
6、為鎖設(shè)置過(guò)期時(shí)間,成功返回 nil;
7、如果1和4的判斷都不滿(mǎn)足,那么返回鎖的的剩余時(shí)間;

unLock

@Override
public void unlock() {
    try {
        get(unlockAsync(Thread.currentThread().getId()));
    } catch (RedisException e) {
        if (e.getCause() instanceof IllegalMonitorStateException) {
            throw (IllegalMonitorStateException) e.getCause();
        } else {
            throw e;
        }
    }
}

@Override
public RFuture<Void> unlockAsync(long threadId) {
    RPromise<Void> result = new RedissonPromise<Void>();
    // 釋放鎖的邏輯主要這里
    RFuture<Boolean> future = unlockInnerAsync(threadId);

    future.onComplete((opStatus, e) -> {
        cancelExpirationRenewal(threadId);

        if (e != null) {
            result.tryFailure(e);
            return;
        }

        if (opStatus == null) {
            IllegalMonitorStateException cause = new IllegalMonitorStateException("attempt to unlock lock, not locked by current thread by node id: "
                    + id + " thread-id: " + threadId);
            result.tryFailure(cause);
            return;
        }

        result.trySuccess(null);
    });

    return result;
}

這里是一系列的調(diào)用,可以直接跳過(guò),直接進(jìn)入到 unlockInnerAsync 函數(shù),看看 unlockInnerAsync 函數(shù)的處理邏輯。

protected RFuture<Boolean> unlockInnerAsync(long threadId) {
    return evalWriteAsync(getName(), LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN,
            "if (redis.call('hexists', KEYS[1], ARGV[3]) == 0) then " +
                    "return nil;" +
                    "end; " +
                    "local counter = redis.call('hincrby', KEYS[1], ARGV[3], -1); " +
                    "if (counter > 0) then " +
                    "redis.call('pexpire', KEYS[1], ARGV[2]); " +
                    "return 0; " +
                    "else " +
                    "redis.call('del', KEYS[1]); " +
                    "redis.call('publish', KEYS[2], ARGV[1]); " +
                    "return 1; " +
                    "end; " +
                    "return nil;",
            Arrays.asList(getName(), getChannelName()), LockPubSub.UNLOCK_MESSAGE, internalLockLeaseTime, getLockName(threadId));
}

該函數(shù)主要執(zhí)行 lua 腳本,腳本的邏輯為:

1、redis.call(&lsquo;hexists&rsquo;, KEYS[1], ARGV[3]) == 0 用于判斷鎖是否為當(dāng)前客戶(hù)端持有,等于 0 說(shuō)明不是直接返回 nil,否則說(shuō)明是,走步驟 2;
2、對(duì)鎖進(jìn)行 -1 操作,并且獲取其計(jì)數(shù) counter;
3、判斷 counter > 0,如果大于 0 說(shuō)明該客戶(hù)端多次獲取鎖,對(duì)鎖進(jìn)行續(xù)期并且返回 0,因?yàn)榇藭r(shí)業(yè)務(wù)還沒(méi)有執(zhí)行完畢,否則走步驟 4;
4、如果count 小于等于 0 則刪除鎖,發(fā)送釋放鎖的消息,返回 1;
5、如果以上邏輯都不滿(mǎn)足,那么直接返回nil。

“Redisson加鎖解鎖怎么實(shí)現(xiàn)”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

向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