转载自http://zhidao.baidu.com/link?url=m56mmWYwRgCymsaLZ2tx-GWDy5FYmUWGovEtuApjTpktHS3bhofrCS-QVGiLoWeS0P-9xeS3p1n8eDqZv-D9KlHXGFYT-1BjC1xmKTnHNkG和http://blog.csdn.net/java2000_wl/article/details/8740911
Redis有一系列的命令,特点是以NX结尾,NX是Not eXists的缩写,如SETNX命令就应该理解为:SET if Not eXists。这系列的命令非常有用,这里讲使用SETNX来实现分布式锁。 用SETNX实现分布式锁 利用SETNX非常简单地实现分布式锁。例如:某客户端要获得一个名字foo的锁,客户端使用下面的命令进行获取: SETNX lock.foo <current Unix time + lock timeout + 1> 如返回1,则该客户端获得锁,把lock.foo的键值设置为时间值表示该键已被锁定,该客户端最后可以通过DEL lock.foo来释放该锁。 如返回0,表明该锁已被其他客户端取得,这时我们可以先返回或进行重试等对方完成或等待锁超时。解决死锁 上面的锁定逻辑有一个问题:如果一个持有锁的客户端失败或崩溃了不能释放锁,该怎么解决?我们可以通过锁的键对应的时间戳来判断这种情况是否发生了,如果当前的时间已经大于lock.foo的值,说明该锁已失效,可以被重新使用。 发生这种情况时,可不能简单的通过DEL来删除锁,然后再SETNX一次,当多个客户端检测到锁超时后都会尝试去释放它,这里就可能出现一个竞态条件,让我们模拟一下这个场景: C0操作超时了,但它还持有着锁,C1和C2读取lock.foo检查时间戳,先后发现超时了。 C1 发送DEL lock.foo C1 发送SETNX lock.foo 并且成功了。 C2 发送DEL lock.foo C2 发送SETNX lock.foo 并且成功了。这样一来,C1,C2都拿到了锁!问题大了! 幸好这种问题是可以避免D,让我们来看看C3这个客户端是怎样做的: C3发送SETNX lock.foo 想要获得锁,由于C0还持有锁,所以Redis返回给C3一个0C3发送GET lock.foo 以检查锁是否超时了,如果没超时,则等待或重试。反之,如果已超时,C3通过下面的操作来尝试获得锁:GETSET lock.foo <current Unix time + lock timeout + 1>通过GETSET,C3拿到的时间戳如果仍然是超时的,那就说明,C3如愿以偿拿到锁了。如果在C3之前,有个叫C4的客户端比C3快一步执行了上面的操作,那么C3拿到的时间戳是个未超时的值,这时,C3没有如期获得锁,需要再次等待或重试。留意一下,尽管C3没拿到锁,但它改写了C4设置的锁的超时值,不过这一点非常微小的误差带来的影响可以忽略不计。注意:为了让分布式锁的算法更稳键些,持有锁的客户端在解锁之前应该再检查一次自己的锁是否已经超时,再去做DEL操作,因为可能客户端因为某个耗时的操作而挂起,操作完的时候锁因为超时已经被别人获得,这时就不必解锁了。 示例伪代码 根据上面的代码,我写了一小段Fake代码来描述使用分布式锁的全过程: # get locklock = 0while lock != 1: timestamp = current Unix time + lock timeout + 1 lock = SETNX lock.foo timestamp if lock == 1 or (now() > (GET lock.foo) and now() > (GETSET lock.foo timestamp)): break; else: sleep(10ms) # do your jobdo_job() # releaseif now() < GET lock.foo: DEL lock.foo是的,要想这段逻辑可以重用,使用python的你马上就想到了Decorator,而用Java的你是不是也想到了那谁?AOP + annotation?行,怎样舒服怎样用吧,别重复代码就行。 ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
- /**
- * @author http://blog.csdn.net/java2000_wl
- * @version <b>1.0.0</b>
- */
- public class RedisBillLockHandler implements IBatchBillLockHandler {
- private static final Logger LOGGER = LoggerFactory.getLogger(RedisBillLockHandler.class);
- private static final int DEFAULT_SINGLE_EXPIRE_TIME = 3;
- private static final int DEFAULT_BATCH_EXPIRE_TIME = 6;
- private final JedisPool jedisPool;
- /**
- * 构造
- * @author http://blog.csdn.net/java2000_wl
- */
- public RedisBillLockHandler(JedisPool jedisPool) {
- this.jedisPool = jedisPool;
- }
- /**
- * 获取锁 如果锁可用 立即返回true, 否则返回false
- * @author http://blog.csdn.net/java2000_wl
- * @param billIdentify
- * @return
- */
- public boolean tryLock(IBillIdentify billIdentify) {
- return tryLock(billIdentify, 0L, null);
- }
- /**
- * 锁在给定的等待时间内空闲,则获取锁成功 返回true, 否则返回false
- * @author http://blog.csdn.net/java2000_wl
- * @param billIdentify
- * @param timeout
- * @param unit
- * @return
- */
- public boolean tryLock(IBillIdentify billIdentify, long timeout, TimeUnit unit) {
- String key = (String) billIdentify.uniqueIdentify();
- Jedis jedis = null;
- try {
- jedis = getResource();
- long nano = System.nanoTime();
- do {
- LOGGER.debug("try lock key: " + key);
- Long i = jedis.setnx(key, key);
- if (i == 1) {
- jedis.expire(key, DEFAULT_SINGLE_EXPIRE_TIME);
- LOGGER.debug("get lock, key: " + key + " , expire in " + DEFAULT_SINGLE_EXPIRE_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(300);
- } while ((System.nanoTime() - nano) < unit.toNanos(timeout));
- return Boolean.FALSE;
- } catch (JedisConnectionException je) {
- LOGGER.error(je.getMessage(), je);
- returnBrokenResource(jedis);
- } catch (Exception e) {
- LOGGER.error(e.getMessage(), e);
- } finally {
- returnResource(jedis);
- }
- return Boolean.FALSE;
- }
- /**
- * 如果锁空闲立即返回 获取失败 一直等待
- * @author http://blog.csdn.net/java2000_wl
- * @param billIdentify
- */
- public void lock(IBillIdentify billIdentify) {
- String key = (String) billIdentify.uniqueIdentify();
- Jedis jedis = null;
- try {
- jedis = getResource();
- do {
- LOGGER.debug("lock key: " + key);
- Long i = jedis.setnx(key, key);
- if (i == 1) {
- jedis.expire(key, DEFAULT_SINGLE_EXPIRE_TIME);
- LOGGER.debug("get lock, key: " + key + " , expire in " + DEFAULT_SINGLE_EXPIRE_TIME + " seconds.");
- return;
- } else {
- if (LOGGER.isDebugEnabled()) {
- String desc = jedis.get(key);
- LOGGER.debug("key: " + key + " locked by another business:" + desc);
- }
- }
- Thread.sleep(300);
- } while (true);
- } catch (JedisConnectionException je) {
- LOGGER.error(je.getMessage(), je);
- returnBrokenResource(jedis);
- } catch (Exception e) {
- LOGGER.error(e.getMessage(), e);
- } finally {
- returnResource(jedis);
- }
- }
- /**
- * 释放锁
- * @author http://blog.csdn.net/java2000_wl
- * @param billIdentify
- */
- public void unLock(IBillIdentify billIdentify) {
- List<IBillIdentify> list = new ArrayList<IBillIdentify>();
- list.add(billIdentify);
- unLock(list);
- }
- /**
- * 批量获取锁 如果全部获取 立即返回true, 部分获取失败 返回false
- * @author http://blog.csdn.net/java2000_wl
- * @date 2013-7-22 下午10:27:44
- * @param billIdentifyList
- * @return
- */
- public boolean tryLock(List<IBillIdentify> billIdentifyList) {
- return tryLock(billIdentifyList, 0L, null);
- }
- /**
- * 锁在给定的等待时间内空闲,则获取锁成功 返回true, 否则返回false
- * @author http://blog.csdn.net/java2000_wl
- * @param billIdentifyList
- * @param timeout
- * @param unit
- * @return
- */
- public boolean tryLock(List<IBillIdentify> billIdentifyList, long timeout, TimeUnit unit) {
- Jedis jedis = null;
- try {
- List<String> needLocking = new CopyOnWriteArrayList<String>();
- List<String> locked = new CopyOnWriteArrayList<String>();
- jedis = getResource();
- long nano = System.nanoTime();
- do {
- // 构建pipeline,批量提交
- Pipeline pipeline = jedis.pipelined();
- for (IBillIdentify identify : billIdentifyList) {
- String key = (String) identify.uniqueIdentify();
- needLocking.add(key);
- pipeline.setnx(key, key);
- }
- LOGGER.debug("try lock keys: " + needLocking);
- // 提交redis执行计数
- List<Object> results = pipeline.syncAndReturnAll();
- for (int i = 0; i < results.size(); ++i) {
- Long result = (Long) results.get(i);
- String key = needLocking.get(i);
- if (result == 1) { // setnx成功,获得锁
- jedis.expire(key, DEFAULT_BATCH_EXPIRE_TIME);
- locked.add(key);
- }
- }
- needLocking.removeAll(locked); // 已锁定资源去除
- if (CollectionUtils.isEmpty(needLocking)) {
- return true;
- } else {
- // 部分资源未能锁住
- LOGGER.debug("keys: " + needLocking + " locked by another business:");
- }
- if (timeout == 0) {
- break;
- }
- Thread.sleep(500);
- } while ((System.nanoTime() - nano) < unit.toNanos(timeout));
- // 得不到锁,释放锁定的部分对象,并返回失败
- if (!CollectionUtils.isEmpty(locked)) {
- jedis.del(locked.toArray(new String[0]));
- }
- return false;
- } catch (JedisConnectionException je) {
- LOGGER.error(je.getMessage(), je);
- returnBrokenResource(jedis);
- } catch (Exception e) {
- LOGGER.error(e.getMessage(), e);
- } finally {
- returnResource(jedis);
- }
- return true;
- }
- /**
- * 批量释放锁
- * @author http://blog.csdn.net/java2000_wl
- * @param billIdentifyList
- */
- public void unLock(List<IBillIdentify> billIdentifyList) {
- List<String> keys = new CopyOnWriteArrayList<String>();
- for (IBillIdentify identify : billIdentifyList) {
- String key = (String) identify.uniqueIdentify();
- keys.add(key);
- }
- Jedis jedis = null;
- try {
- jedis = getResource();
- jedis.del(keys.toArray(new String[0]));
- LOGGER.debug("release lock, keys :" + keys);
- } catch (JedisConnectionException je) {
- LOGGER.error(je.getMessage(), je);
- returnBrokenResource(jedis);
- } catch (Exception e) {
- LOGGER.error(e.getMessage(), e);
- } finally {
- returnResource(jedis);
- }
- }
- /**
- * @author http://blog.csdn.net/java2000_wl
- * @date 2013-7-22 下午9:33:45
- * @return
- */
- private Jedis getResource() {
- return jedisPool.getResource();
- }
- /**
- * 销毁连接
- * @author http://blog.csdn.net/java2000_wl
- * @param jedis
- */
- private void returnBrokenResource(Jedis jedis) {
- if (jedis == null) {
- return;
- }
- try {
- //容错
- jedisPool.returnBrokenResource(jedis);
- } catch (Exception e) {
- LOGGER.error(e.getMessage(), e);
- }
- }
- /**
- * @author http://blog.csdn.net/java2000_wl
- * @param jedis
- */
- private void returnResource(Jedis jedis) {
- if (jedis == null) {
- return;
- }
- try {
- jedisPool.returnResource(jedis);
- } catch (Exception e) {
- LOGGER.error(e.getMessage(), e);
- }
- }
时间: 2024-11-05 17:19:09