java redis 分布式锁 实现原理_Redis分布式锁实现原理 java版

说明: Redis因为是单线程的,所以本身没有锁的概念。 所以分布式锁的实现原理是

往Redis当中写入一个key(调用方法setnx),写入成功相当于获取锁成功。写入失败也即是setnx方法返回0,获取锁失败。

注意锁的失效时间,否则容易造成死锁。

/**

* 锁在给定的等待时间内空闲,则获取锁成功 返回true, 否则返回false

* @param subKey

* @param timeout 如果timeout=0,取不到锁时,不等待,直接返回.

* @param unit

* @return

*/

public boolean tryLock(String subKey, long timeout, TimeUnit unit) {

String key = LOCK_KEY + subKey;

Jedis jedis = null;

try {

jedis = getConnection();

if (jedis == null) {

return Boolean.FALSE;

}

long nano = System.nanoTime();

do {

logger.debug("try lock key: " + key);

Long i = jedis.setnx(key, key);

if (i == 1) {

jedis.expire(key, EXPIRED_TIME);

logger.debug("get lock, key: " + key + " , expire in " + EXPIRED_TIME + " seconds.");

return Boolean.TRUE;

} else { // 存在锁

if (logger.isDebugEnabled()) {

String desc = jedis.get(key);

logger.debug("key: " + key + " locked by another business:" + desc);

}

}

if (timeout == 0) { //取不到锁时,不等待,直接返回.

break;

}

Thread.sleep(200);

} while ((System.nanoTime() - nano) < unit.toNanos(timeout));//取不到锁时等待,直到timeout

return Boolean.FALSE;

} catch (JedisConnectionException je) {

logger.error(je.getMessage(), je);

returnBorkenConnection(jedis);

} catch (Exception e) {

logger.error(e.getMessage(), e);

} finally {

returnConnection(jedis);

}

return Boolean.FALSE;

}

/**

* 如果锁空闲立即返回 获取失败 一直等待

* @param subKey

*/

public boolean lock(String subKey) {

String key = LOCK_KEY + subKey;

Jedis jedis = null;

boolean isLock = false;

try {

jedis = getConnection();

if (jedis == null) {

return isLock;

}

while (true) {

logger.debug("lock key: " + key);

Long i = jedis.setnx(key, key);

if (i == 1) {

jedis.expire(key, EXPIRED_TIME);

logger.debug("get lock, key: " + key + " , expire in " + EXPIRED_TIME + " seconds.");

isLock = true;

} else {

if (logger.isDebugEnabled()) {

String desc = jedis.get(key);

logger.debug("key: " + key + " locked by another business:" + desc);

}

isLock = false;

}

Thread.sleep(500);

}

} catch (JedisConnectionException je) {

logger.error(je.getMessage(), je);

returnBorkenConnection(jedis);

} catch (Exception e) {

logger.error(e.getMessage(), e);

} finally {

returnConnection(jedis);

}

return isLock;

}

/**

* 释放锁

* @param subKey

*/

public void unLock(String subKey) {

String key = LOCK_KEY + subKey;

Jedis jedis = null;

try {

jedis = getConnection();

if (jedis == null) {

return;

}

jedis.del(key);

logger.debug("release lock, keys :" + key);

} catch (JedisConnectionException je) {

logger.error(je.getMessage(), je);

returnBorkenConnection(jedis);

} catch (Exception e) {

logger.error(e.getMessage(), e);

} finally {

returnConnection(jedis);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值