[转载] Redis实现分布式锁

转载自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一个0
C3发送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 lock
lock = 0
while 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 job
do_job()

# release
if now() < GET lock.foo:
DEL lock.foo
是的,要想这段逻辑可以重用,使用python的你马上就想到了Decorator,而用Java的你是不是也想到了那谁?AOP + annotation?行,怎样舒服怎样用吧,别重复代码就行。

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

  1. /** 
  2.  * @author http://blog.csdn.net/java2000_wl 
  3.  * @version <b>1.0.0</b> 
  4.  */  
  5. public class RedisBillLockHandler implements IBatchBillLockHandler {  
  6.   
  7.     private static final Logger LOGGER = LoggerFactory.getLogger(RedisBillLockHandler.class);  
  8.   
  9.     private static final int DEFAULT_SINGLE_EXPIRE_TIME = 3;  
  10.       
  11.     private static final int DEFAULT_BATCH_EXPIRE_TIME = 6;  
  12.   
  13.     private final JedisPool jedisPool;  
  14.       
  15.     /** 
  16.      * 构造 
  17.      * @author http://blog.csdn.net/java2000_wl 
  18.      */  
  19.     public RedisBillLockHandler(JedisPool jedisPool) {  
  20.         this.jedisPool = jedisPool;  
  21.     }  
  22.   
  23.     /** 
  24.      * 获取锁  如果锁可用   立即返回true,  否则返回false 
  25.      * @author http://blog.csdn.net/java2000_wl 
  26.      * @param billIdentify 
  27.      * @return 
  28.      */  
  29.     public boolean tryLock(IBillIdentify billIdentify) {  
  30.         return tryLock(billIdentify, 0L, null);  
  31.     }  
  32.   
  33.     /** 
  34.      * 锁在给定的等待时间内空闲,则获取锁成功 返回true, 否则返回false 
  35.      * @author http://blog.csdn.net/java2000_wl 
  36.      * @param billIdentify 
  37.      * @param timeout 
  38.      * @param unit 
  39.      * @return 
  40.      */  
  41.     public boolean tryLock(IBillIdentify billIdentify, long timeout, TimeUnit unit) {  
  42.         String key = (String) billIdentify.uniqueIdentify();  
  43.         Jedis jedis = null;  
  44.         try {  
  45.             jedis = getResource();  
  46.             long nano = System.nanoTime();  
  47.             do {  
  48.                 LOGGER.debug("try lock key: " + key);  
  49.                 Long i = jedis.setnx(key, key);  
  50.                 if (i == 1) {   
  51.                     jedis.expire(key, DEFAULT_SINGLE_EXPIRE_TIME);  
  52.                     LOGGER.debug("get lock, key: " + key + " , expire in " + DEFAULT_SINGLE_EXPIRE_TIME + " seconds.");  
  53.                     return Boolean.TRUE;  
  54.                 } else { // 存在锁  
  55.                     if (LOGGER.isDebugEnabled()) {  
  56.                         String desc = jedis.get(key);  
  57.                         LOGGER.debug("key: " + key + " locked by another business:" + desc);  
  58.                     }  
  59.                 }  
  60.                 if (timeout == 0) {  
  61.                     break;  
  62.                 }  
  63.                 Thread.sleep(300);  
  64.             } while ((System.nanoTime() - nano) < unit.toNanos(timeout));  
  65.             return Boolean.FALSE;  
  66.         } catch (JedisConnectionException je) {  
  67.             LOGGER.error(je.getMessage(), je);  
  68.             returnBrokenResource(jedis);  
  69.         } catch (Exception e) {  
  70.             LOGGER.error(e.getMessage(), e);  
  71.         } finally {  
  72.             returnResource(jedis);  
  73.         }  
  74.         return Boolean.FALSE;  
  75.     }  
  76.   
  77.     /** 
  78.      * 如果锁空闲立即返回   获取失败 一直等待 
  79.      * @author http://blog.csdn.net/java2000_wl 
  80.      * @param billIdentify 
  81.      */  
  82.     public void lock(IBillIdentify billIdentify) {  
  83.         String key = (String) billIdentify.uniqueIdentify();  
  84.         Jedis jedis = null;  
  85.         try {  
  86.             jedis = getResource();  
  87.             do {  
  88.                 LOGGER.debug("lock key: " + key);  
  89.                 Long i = jedis.setnx(key, key);  
  90.                 if (i == 1) {   
  91.                     jedis.expire(key, DEFAULT_SINGLE_EXPIRE_TIME);  
  92.                     LOGGER.debug("get lock, key: " + key + " , expire in " + DEFAULT_SINGLE_EXPIRE_TIME + " seconds.");  
  93.                     return;  
  94.                 } else {  
  95.                     if (LOGGER.isDebugEnabled()) {  
  96.                         String desc = jedis.get(key);  
  97.                         LOGGER.debug("key: " + key + " locked by another business:" + desc);  
  98.                     }  
  99.                 }  
  100.                 Thread.sleep(300);   
  101.             } while (true);  
  102.         } catch (JedisConnectionException je) {  
  103.             LOGGER.error(je.getMessage(), je);  
  104.             returnBrokenResource(jedis);  
  105.         } catch (Exception e) {  
  106.             LOGGER.error(e.getMessage(), e);  
  107.         } finally {  
  108.             returnResource(jedis);  
  109.         }  
  110.     }  
  111.   
  112.     /** 
  113.      * 释放锁 
  114.      * @author http://blog.csdn.net/java2000_wl 
  115.      * @param billIdentify 
  116.      */  
  117.     public void unLock(IBillIdentify billIdentify) {  
  118.         List<IBillIdentify> list = new ArrayList<IBillIdentify>();  
  119.         list.add(billIdentify);  
  120.         unLock(list);  
  121.     }  
  122.   
  123.     /** 
  124.      * 批量获取锁  如果全部获取   立即返回true, 部分获取失败 返回false 
  125.      * @author http://blog.csdn.net/java2000_wl 
  126.      * @date 2013-7-22 下午10:27:44 
  127.      * @param billIdentifyList 
  128.      * @return 
  129.      */  
  130.     public boolean tryLock(List<IBillIdentify> billIdentifyList) {  
  131.         return tryLock(billIdentifyList, 0L, null);  
  132.     }  
  133.       
  134.     /** 
  135.      * 锁在给定的等待时间内空闲,则获取锁成功 返回true, 否则返回false 
  136.      * @author http://blog.csdn.net/java2000_wl 
  137.      * @param billIdentifyList 
  138.      * @param timeout 
  139.      * @param unit 
  140.      * @return 
  141.      */  
  142.     public boolean tryLock(List<IBillIdentify> billIdentifyList, long timeout, TimeUnit unit) {  
  143.         Jedis jedis = null;  
  144.         try {  
  145.             List<String> needLocking = new CopyOnWriteArrayList<String>();    
  146.             List<String> locked = new CopyOnWriteArrayList<String>();     
  147.             jedis = getResource();  
  148.             long nano = System.nanoTime();  
  149.             do {  
  150.                 // 构建pipeline,批量提交  
  151.                 Pipeline pipeline = jedis.pipelined();  
  152.                 for (IBillIdentify identify : billIdentifyList) {  
  153.                     String key = (String) identify.uniqueIdentify();  
  154.                     needLocking.add(key);  
  155.                     pipeline.setnx(key, key);  
  156.                 }  
  157.                 LOGGER.debug("try lock keys: " + needLocking);  
  158.                 // 提交redis执行计数  
  159.                 List<Object> results = pipeline.syncAndReturnAll();  
  160.                 for (int i = 0; i < results.size(); ++i) {  
  161.                     Long result = (Long) results.get(i);  
  162.                     String key = needLocking.get(i);  
  163.                     if (result == 1) {  // setnx成功,获得锁  
  164.                         jedis.expire(key, DEFAULT_BATCH_EXPIRE_TIME);  
  165.                         locked.add(key);  
  166.                     }   
  167.                 }  
  168.                 needLocking.removeAll(locked);  // 已锁定资源去除  
  169.                   
  170.                 if (CollectionUtils.isEmpty(needLocking)) {  
  171.                     return true;  
  172.                 } else {      
  173.                     // 部分资源未能锁住  
  174.                     LOGGER.debug("keys: " + needLocking + " locked by another business:");  
  175.                 }  
  176.                   
  177.                 if (timeout == 0) {   
  178.                     break;  
  179.                 }  
  180.                 Thread.sleep(500);    
  181.             } while ((System.nanoTime() - nano) < unit.toNanos(timeout));  
  182.   
  183.             // 得不到锁,释放锁定的部分对象,并返回失败  
  184.             if (!CollectionUtils.isEmpty(locked)) {  
  185.                 jedis.del(locked.toArray(new String[0]));  
  186.             }  
  187.             return false;  
  188.         } catch (JedisConnectionException je) {  
  189.             LOGGER.error(je.getMessage(), je);  
  190.             returnBrokenResource(jedis);  
  191.         } catch (Exception e) {  
  192.             LOGGER.error(e.getMessage(), e);  
  193.         } finally {  
  194.             returnResource(jedis);  
  195.         }  
  196.         return true;  
  197.     }  
  198.   
  199.     /** 
  200.      * 批量释放锁 
  201.      * @author http://blog.csdn.net/java2000_wl 
  202.      * @param billIdentifyList 
  203.      */  
  204.     public void unLock(List<IBillIdentify> billIdentifyList) {  
  205.         List<String> keys = new CopyOnWriteArrayList<String>();  
  206.         for (IBillIdentify identify : billIdentifyList) {  
  207.             String key = (String) identify.uniqueIdentify();  
  208.             keys.add(key);  
  209.         }  
  210.         Jedis jedis = null;  
  211.         try {  
  212.             jedis = getResource();  
  213.             jedis.del(keys.toArray(new String[0]));  
  214.             LOGGER.debug("release lock, keys :" + keys);  
  215.         } catch (JedisConnectionException je) {  
  216.             LOGGER.error(je.getMessage(), je);  
  217.             returnBrokenResource(jedis);  
  218.         } catch (Exception e) {  
  219.             LOGGER.error(e.getMessage(), e);  
  220.         } finally {  
  221.             returnResource(jedis);  
  222.         }  
  223.     }  
  224.       
  225.     /** 
  226.      * @author http://blog.csdn.net/java2000_wl 
  227.      * @date 2013-7-22 下午9:33:45 
  228.      * @return 
  229.      */  
  230.     private Jedis getResource() {  
  231.         return jedisPool.getResource();  
  232.     }  
  233.       
  234.     /** 
  235.      * 销毁连接 
  236.      * @author http://blog.csdn.net/java2000_wl 
  237.      * @param jedis 
  238.      */  
  239.     private void returnBrokenResource(Jedis jedis) {  
  240.         if (jedis == null) {  
  241.             return;  
  242.         }  
  243.         try {  
  244.             //容错  
  245.             jedisPool.returnBrokenResource(jedis);  
  246.         } catch (Exception e) {  
  247.             LOGGER.error(e.getMessage(), e);  
  248.         }  
  249.     }  
  250.       
  251.     /** 
  252.      * @author http://blog.csdn.net/java2000_wl 
  253.      * @param jedis 
  254.      */  
  255.     private void returnResource(Jedis jedis) {  
  256.         if (jedis == null) {  
  257.             return;  
  258.         }  
  259.         try {  
  260.             jedisPool.returnResource(jedis);  
  261.         } catch (Exception e) {  
  262.             LOGGER.error(e.getMessage(), e);  
  263.         }  
  264.     }  

 

posted on 2015-09-15 09:51  追求卓越,厚积薄发  阅读(357)  评论(0编辑  收藏  举报

导航