redis分散ロック実装-面接問題
1821 ワード
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() {
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)