分布式锁的三种实现方式

来源:互联网 发布:人工智能替代人类 编辑:程序博客网 时间:2024/03/29 06:57



一、zookeeper

1、实现原理:

基于zookeeper瞬时有序节点实现的分布式锁,其主要逻辑如下(该图来自于IBM网站)。大致思想即为:每个客户端对某个功能加锁时,在zookeeper上的与该功能对应的指定节点的目录下,生成一个唯一的瞬时有序节点。判断是否获取锁的方式很简单,只需要判断有序节点中序号最小的一个。当释放锁的时候,只需将这个瞬时节点删除即可。同时,其可以避免服务宕机导致的锁无法释放,而产生的死锁问题。

2、优点

锁安全性高,zk可持久化

3、缺点

性能开销比较高。因为其需要动态产生、销毁瞬时节点来实现锁功能。

4、实现

可以直接采用zookeeper第三方库curator即可方便地实现分布式锁。以下为基于curator实现的zk分布式锁核心代码:

 

Java代码  收藏代码
  1. @Override  
  2. public boolean tryLock(LockInfo info) {  
  3.     InterProcessMutex mutex = getMutex(info);  
  4.     int tryTimes = info.getTryTimes();  
  5.     long tryInterval = info.getTryInterval();  
  6.     boolean flag = true;// 代表是否需要重试  
  7.     while (flag && --tryTimes >= 0) {  
  8.         try {  
  9.             if (mutex.acquire(info.getWaitLockTime(), TimeUnit.MILLISECONDS)) {  
  10.                 LOGGER.info(LogConstant.DST_LOCK + "acquire lock successfully!");  
  11.                 flag = false;  
  12.                 break;  
  13.             }  
  14.         } catch (Exception e) {  
  15.             LOGGER.error(LogConstant.DST_LOCK + "acquire lock error!", e);  
  16.         } finally {  
  17.             checkAndRetry(flag, tryInterval, tryTimes);  
  18.         }  
  19.     }  
  20.     return !flag;// 最后还需要重试,说明没拿到锁  
  21. }  

 

Java代码  收藏代码
  1. @Override  
  2. public boolean releaseLock(LockInfo info) {  
  3.     InterProcessMutex mutex = getMutex(info);  
  4.     int tryTimes = info.getTryTimes();  
  5.     long tryInterval = info.getTryInterval();  
  6.     boolean flag = true;// 代表是否需要重试  
  7.     while (flag && --tryTimes >= 0) {  
  8.         try {  
  9.             mutex.release();  
  10.             LOGGER.info(LogConstant.DST_LOCK + "release lock successfully!");  
  11.             flag = false;  
  12.             break;  
  13.         } catch (Exception e) {  
  14.             LOGGER.error(LogConstant.DST_LOCK + "release lock error!", e);  
  15.         } finally {  
  16.             checkAndRetry(flag, tryInterval, tryTimes);  
  17.         }  
  18.     }  
  19.     return !flag;// 最后还需要重试,说明没拿到锁  
  20. }  

 

Java代码  收藏代码
  1. /** 
  2.      * 获取锁。此处需要加同步,concurrentHashmap无法避免此处的同步问题 
  3.      * @param info 锁信息 
  4.      * @return 锁实例 
  5.      */  
  6.     private synchronized InterProcessMutex getMutex(LockInfo info) {  
  7.         InterProcessReadWriteLock lock = null;  
  8.         if (locksCache.get(info.getLock()) != null) {  
  9.             lock = locksCache.get(info.getLock());  
  10.         } else {  
  11.             lock = new InterProcessReadWriteLock(client, BASE_DIR + info.getLock());  
  12.             locksCache.put(info.getLock(), lock);  
  13.         }  
  14.         InterProcessMutex mutex = null;  
  15.         switch (info.getIsolate()) {  
  16.         case READ:  
  17.             mutex = lock.readLock();  
  18.             break;  
  19.         case WRITE:  
  20.             mutex = lock.writeLock();  
  21.             break;  
  22.         default:  
  23.             throw new IllegalArgumentException();  
  24.         }  
  25.         return mutex;  
  26.     }  

 

Java代码  收藏代码
  1. /** 
  2.  * 判断是否需要重试 
  3.  * @param flag 是否需要重试标志 
  4.  * @param tryInterval 重试间隔 
  5.  * @param tryTimes 重试次数 
  6.  */  
  7. private void checkAndRetry(boolean flag, long tryInterval, int tryTimes) {  
  8.     try {  
  9.         if (flag) {  
  10.             Thread.sleep(tryInterval);  
  11.             LOGGER.info(LogConstant.DST_LOCK + "retry getting lock! now retry time left: " + tryTimes);  
  12.         }  
  13.     } catch (InterruptedException e) {  
  14.         LOGGER.error(LogConstant.DST_LOCK + "retry interval thread interruptted!", e);  
  15.     }  
  16. }  

 

二、memcached分布式锁

1、实现原理:

memcached带有add函数,利用add函数的特性即可实现分布式锁。add和set的区别在于:如果多线程并发set,则每个set都会成功,但最后存储的值以最后的set的线程为准。而add的话则相反,add会添加第一个到达的值,并返回true,后续的添加则都会返回false。利用该点即可很轻松地实现分布式锁。

2、优点

并发高效。

3、缺点

(1)memcached采用列入LRU置换策略,所以如果内存不够,可能导致缓存中的锁信息丢失。

(2)memcached无法持久化,一旦重启,将导致信息丢失。

 

三、redis分布式锁

redis分布式锁即可以结合zk分布式锁锁高度安全和memcached并发场景下效率很好的优点,可以利用jedis客户端实现。参考http://blog.csdn.net/java2000_wl/article/details/8740911

  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.     }  

原创粉丝点击