redis setnx 分佈式鎖

    private final String RedisLockKey = "RedLock";
    private final long altTimeout = 1 * 60 * 60 * 1000L;// 1hour

    /**
     * 獲取redis分佈式鎖
     * 
     * @author Administrator
     * @version 1.0
     * @return true:得到鎖權限 false:未得到鎖權限
     */
    private synchronized boolean getRedLock() {
        Long flag = jedis.setnx(RedisLockKey, String.valueOf(System.currentTimeMillis() + altTimeout + 1L));
        if (flag == 0L) {
            String value = jedis.get(RedisLockKey);
            long longVal = Long.parseLong(value);
            if (longVal > System.currentTimeMillis()) {// 未過時
                return Boolean.FALSE;
            } else {// 過時
                String _value =
                    jedis.getSet(RedisLockKey, String.valueOf(System.currentTimeMillis() + altTimeout + 1L));
                long _longVal = Long.parseLong(_value);
                if (_longVal > System.currentTimeMillis()) {
                    return Boolean.FALSE;
                } else {
                    return Boolean.TRUE;
                }
            }
        } else {
            return Boolean.TRUE;
        }
    }
相關文章
相關標籤/搜索