日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關咨詢
選擇下列產(chǎn)品馬上在線溝通
服務時間:8:30-17:00
你可能遇到了下面的問題
關閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
一文詳解分布式鎖的看門狗機制

我們今天來看看這個 Redis 的看門狗機制,畢竟現(xiàn)在還是有很多是會使用 Redis 來實現(xiàn)分布式鎖的,我們現(xiàn)在看看這個 Redis 是怎么實現(xiàn)分布式鎖的,然后我們再來分析這個 Redis 的看門狗機制,如果沒有這個機制,很多使用 Redis 來做分布式鎖的小伙伴們,經(jīng)常給導致死鎖。

Redis 實現(xiàn)分布式鎖

Redis實現(xiàn)分布式鎖,最主要的就是這幾個條件

獲取鎖

  • 互斥:確保只能有一個線程獲取鎖
  • 非阻塞:嘗試一次,成功返回true,失敗返回false

釋放鎖

  • 手動釋放
  • 超時釋放:獲取鎖時添加一個超時時間

上代碼:

@Resource
    private RedisTemplate redisTemplate;

    public static final String UNLOCK_LUA;

    /**
     * 釋放鎖腳本,原子操作
     */
    static {
        StringBuilder sb = new StringBuilder();
        sb.append("if redis.call(\"get\",KEYS[1]) == ARGV[1] ");
        sb.append("then ");
        sb.append("    return redis.call(\"del\",KEYS[1]) ");
        sb.append("else ");
        sb.append("    return 0 ");
        sb.append("end ");
        UNLOCK_LUA = sb.toString();
    }


    /**
     * 獲取分布式鎖,原子操作
     * @param lockKey
     * @param requestId 唯一ID, 可以使用UUID.randomUUID().toString();
     * @param expire
     * @param timeUnit
     * @return
     */
    public boolean tryLock(String lockKey, String requestId, long expire, TimeUnit timeUnit) {
        try{
            RedisCallback callback = (connection) -> {
                return connection.set(lockKey.getBytes(Charset.forName("UTF-8")), requestId.getBytes(Charset.forName("UTF-8")), Expiration.seconds(timeUnit.toSeconds(expire)), RedisStringCommands.SetOption.SET_IF_ABSENT);
            };
            return (Boolean)redisTemplate.execute(callback);
        } catch (Exception e) {
            log.error("redis lock error.", e);
        }
        return false;
    }

    /**
     * 釋放鎖
     * @param lockKey
     * @param requestId 唯一ID
     * @return
     */
    public boolean releaseLock(String lockKey, String requestId) {
        RedisCallback callback = (connection) -> {
            return connection.eval(UNLOCK_LUA.getBytes(), ReturnType.BOOLEAN ,1, lockKey.getBytes(Charset.forName("UTF-8")), requestId.getBytes(Charset.forName("UTF-8")));
        };
        return (Boolean)redisTemplate.execute(callback);
    }

    /**
     * 獲取Redis鎖的value值
     * @param lockKey
     * @return
     */
    public String get(String lockKey) {
        try {
            RedisCallback callback = (connection) -> {
                return new String(connection.get(lockKey.getBytes()), Charset.forName("UTF-8"));
            };
            return (String)redisTemplate.execute(callback);
        } catch (Exception e) {
            log.error("get redis occurred an exception", e);
        }
        return null;
    }

這種實現(xiàn)方式就是相當于我們直接使用 Redis 來自己實現(xiàn)的分布式鎖,但是也不是沒有框架給我們來實現(xiàn),那就是Redission。而看門狗機制是Redission提供的一種自動延期機制,這個機制使得Redission提供的分布式鎖是可以自動續(xù)期的。

為什么需要看門狗機制

分布式鎖是不能設置永不過期的,這是為了避免在分布式的情況下,一個節(jié)點獲取鎖之后宕機從而出現(xiàn)死鎖的情況,所以需要個分布式鎖設置一個過期時間。但是這樣會導致一個線程拿到鎖后,在鎖的過期時間到達的時候程序還沒運行完,導致鎖超時釋放了,那么其他線程就能獲取鎖進來,從而出現(xiàn)問題。

所以,看門狗機制的自動續(xù)期,就很好地解決了這一個問題。

Redisson已經(jīng)幫我們實現(xiàn)了這個分布式鎖,我們需要的就是調(diào)用,那么我們來看看 Redisson 的源碼,他是如何來實現(xiàn)看門狗機制的。

tryLock

RedissonLock類下:

public boolean tryLock(long waitTime, TimeUnit unit) throws InterruptedException {
    return tryLock(waitTime, -1, unit);
}
  • waitTime:獲取鎖的最大等待時間(沒有傳默認為-1)
  • leaseTime:鎖自動釋放的時間(沒有傳的話默認-1)
  • unit:時間的單位(等待時間和鎖自動釋放的時間單位)
@Override
    public boolean tryLock(long waitTime, long leaseTime, TimeUnit unit) throws InterruptedException {
        long time = unit.toMillis(waitTime);
        long current = System.currentTimeMillis();
        long threadId = Thread.currentThread().getId();
        Long ttl = tryAcquire(waitTime, leaseTime, unit, threadId);
        // lock acquired
        if (ttl == null) {
            return true;
        }
        
        time -= System.currentTimeMillis() - current;
        if (time <= 0) {
            acquireFailed(waitTime, unit, threadId);
            return false;
        }
        
        current = System.currentTimeMillis();
        RFuture subscribeFuture = subscribe(threadId);
        if (!subscribeFuture.await(time, TimeUnit.MILLISECONDS)) {
            if (!subscribeFuture.cancel(false)) {
                subscribeFuture.onComplete((res, e) -> {
                    if (e == null) {
                        unsubscribe(subscribeFuture, threadId);
                    }
                });
            }
            acquireFailed(waitTime, unit, threadId);
            return false;
        }

        try {
            time -= System.currentTimeMillis() - current;
            if (time <= 0) {
                acquireFailed(waitTime, unit, threadId);
                return false;
            }
        
            while (true) {
                long currentTime = System.currentTimeMillis();
                ttl = tryAcquire(waitTime, leaseTime, unit, threadId);
                // lock acquired
                if (ttl == null) {
                    return true;
                }

                time -= System.currentTimeMillis() - currentTime;
                if (time <= 0) {
                    acquireFailed(waitTime, unit, threadId);
                    return false;
                }

                // waiting for message
                currentTime = System.currentTimeMillis();
                if (ttl >= 0 && ttl < time) {
                    subscribeFuture.getNow().getLatch().tryAcquire(ttl, TimeUnit.MILLISECONDS);
                } else {
                    subscribeFuture.getNow().getLatch().tryAcquire(time, TimeUnit.MILLISECONDS);
                }

                time -= System.currentTimeMillis() - currentTime;
                if (time <= 0) {
                    acquireFailed(waitTime, unit, threadId);
                    return false;
                }
            }
        } finally {
            unsubscribe(subscribeFuture, threadId);
        }
//        return get(tryLockAsync(waitTime, leaseTime, unit));
    }

上面這一段代碼最主要的內(nèi)容講述看門狗機制的實際上應該算是 tryAcquire

最終落地為tryAcquireAsync

//如果獲取鎖失敗,返回的結(jié)果是這個key的剩余有效期
        RFuture ttlRemainingFuture = this.tryLockInnerAsync(waitTime, this.commandExecutor.getConnectionManager().getCfg().getLockWatchdogTimeout(), TimeUnit.MILLISECONDS, threadId, RedisCommands.EVAL_LONG);
        //上面獲取鎖回調(diào)成功之后,執(zhí)行這代碼塊的內(nèi)容
        ttlRemainingFuture.onComplete((ttlRemaining, e) -> {
            //不存在異常
            if (e == null) {
                //剩余有效期為null
                if (ttlRemaining == null) {
                    //這個函數(shù)是解決最長等待有效期的問題
                    this.scheduleExpirationRenewal(threadId);
                }

            }
        });
        return ttlRemainingFuture;

調(diào)用tryLockInnerAsync,如果獲取鎖失敗,返回的結(jié)果是這個key的剩余有效期,如果獲取鎖成功,則返回null。

獲取鎖成功后,如果檢測不存在異常并且獲取鎖成功(ttlRemaining == null)。

那么則執(zhí)行this.scheduleExpirationRenewal(threadId);來啟動看門狗機制。

看門狗機制提供的默認超時時間是30*1000毫秒,也就是30秒

如果一個線程獲取鎖后,運行程序到釋放鎖所花費的時間大于鎖自動釋放時間(也就是看門狗機制提供的超時時間30s),那么Redission會自動給redis中的目標鎖延長超時時間。

在Redission中想要啟動看門狗機制,那么我們就不用獲取鎖的時候自己定義leaseTime(鎖自動釋放時間)。

但是 Redisson 和我們自己定義實現(xiàn)分布式鎖不一樣,如果自己定義了鎖自動釋放時間的話,無論是通過lock還是tryLock方法,都無法啟用看門狗機制。

所以你了解分布式鎖的看門狗機制了么?


文章標題:一文詳解分布式鎖的看門狗機制
網(wǎng)站網(wǎng)址:http://www.5511xx.com/article/djpgjop.html