1. 程式人生 > >redis分散式鎖實現-面試題

redis分散式鎖實現-面試題

1 加鎖(key自定義,value為uuid)

Boolean setNX(byte[] key, byte[] value);

2 設定過期時間(key,timeout,unit)

public Boolean expire(K key, final long timeout, final TimeUnit unit) {
		final byte[] rawKey = rawKey(key);
		final long rawTimeout = TimeoutUtils.toMillis(timeout, unit);

		return execute(new RedisCallback<Boolean>() {

			public Boolean doInRedis(RedisConnection connection) {
				try {
					return connection.pExpire(rawKey, rawTimeout);
				} catch (Exception e) {
					// Driver may not support pExpire or we may be running on Redis 2.4
					return connection.expire(rawKey, TimeoutUtils.toSeconds(timeout, unit));
				}
			}
		}, true);
	}

3 釋放鎖(傳入key和value,比較value,若相同,則刪除key)

              distributedLocker.unlock(BalanceAccountConstants.AccountRedisKey.LOCKER_BALANCE_ACCOUNT_LOCK, lockerId);
 public void unlock(String name, String lockerId) {
        String key = getLockerKey(name);
        String value = redis.opsForValue().get(key);

        if (value == null) {
            logger.info("the locker '{}' doesn't exists", name);
            return;
        }

        if (!value.equals(lockerId)) {
            logger.warn("invalid locker id!");
            return;
        }

        redis.delete(key);
        logger.info("the locker '{}' is unlocked", name);
    }
public Long del(byte[]... keys)