溫馨提示×

溫馨提示×

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

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

RedisLock分布式redis鎖

發(fā)布時間:2020-07-17 08:09:16 來源:網(wǎng)絡 閱讀:744 作者:panguixiang 欄目:軟件技術

@Component
public class RedisLock {
Logger logger= LoggerFactory.getLogger(RedisLock.class);
private static final String LOCK_SUCCESS = "OK";
private static final String SET_IF_NOT_EXIST = "NX";//NX是毫秒,EX是秒
private static final String SET_WITH_EXPIRE_TIME = "PX";

/**
 * 嘗試獲取分布式鎖
 * @param lockKey 鎖
 * @param requestId 請求標識
 * @param expireTime 超期時間
 * @return 是否獲取成功
 */
public boolean tryGetDistributedLock(String lockKey, String requestId, int expireTime) {
    Jedis jedis=null;
    try{
        jedis = Const.jedisPoolCommon.getResource();
        String result =jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
        if (LOCK_SUCCESS.equals(result)) {
            return true;
        }
    }catch (Exception ex){
        logger.error("tryGetDistributedLock異常"+ex);
    }finally {
        if(jedis!=null){
            jedis.close();
        }
    }
    return false;
}
private static final Long RELEASE_SUCCESS = 1L;

/**
 * 釋放分布式鎖
 * @param lockKey 鎖
 * @param requestId 請求標識
 * @return 是否釋放成功
 */
public boolean releaseDistributedLock( String lockKey, String requestId) {
    Jedis jedis = null;
    try{
        jedis=Const.jedisPoolCommon.getResource();
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));
        if (RELEASE_SUCCESS.equals(result)) {
            return true;
        }
    }catch (Exception ex){
        logger.error("releaseDistributedLock異常"+ex);
    }finally {
        if(jedis!=null){
            jedis.close();
        }
    }
    return false;
}

}

向AI問一下細節(jié)

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

AI