[转载请注明作者和原文链接,  如有谬误, 欢迎在评论中指正. ]

场景描述

在分布式应用, 往往存在多个进程提供同一服务. 这些进程有可能在相同的机器上, 也有可能分布在不同的机器上. 如果这些进程共享了一些资源, 可能就需要分布式锁来锁定对这些资源的访问.
本文将介绍如何利用zookeeper实现分布式锁.

思路

进程需要访问共享数据时, 就在"/locks"节点下创建一个sequence类型的子节点, 称为thisPath. 当thisPath在所有子节点中最小时, 说明该进程获得了锁. 进程获得锁之后, 就可以访问共享资源了. 访问完成后, 需要将thisPath删除. 锁由新的最小的子节点获得.
有了清晰的思路之后, 还需要补充一些细节. 进程如何知道thisPath是所有子节点中最小的呢? 可以在创建的时候, 通过getChildren方法获取子节点列表, 然后在列表中找到排名比thisPath前1位的节点, 称为waitPath, 然后在waitPath上注册监听, 当waitPath被删除后, 进程获得通知, 此时说明该进程获得了锁.

实现

以一个DistributedClient对象模拟一个进程的形式, 演示zookeeper分布式锁的实现.

  1. public class DistributedClient {
  2. // 超时时间
  3. private static final int SESSION_TIMEOUT = 5000;
  4. // zookeeper server列表
  5. private String hosts = "localhost:4180,localhost:4181,localhost:4182";
  6. private String groupNode = "locks";
  7. private String subNode = "sub";
  8. private ZooKeeper zk;
  9. // 当前client创建的子节点
  10. private String thisPath;
  11. // 当前client等待的子节点
  12. private String waitPath;
  13. private CountDownLatch latch = new CountDownLatch(1);
  14. /**
  15. * 连接zookeeper
  16. */
  17. public void connectZookeeper() throws Exception {
  18. zk = new ZooKeeper(hosts, SESSION_TIMEOUT, new Watcher() {
  19. public void process(WatchedEvent event) {
  20. try {
  21. // 连接建立时, 打开latch, 唤醒wait在该latch上的线程
  22. if (event.getState() == KeeperState.SyncConnected) {
  23. latch.countDown();
  24. }
  25. // 发生了waitPath的删除事件
  26. if (event.getType() == EventType.NodeDeleted && event.getPath().equals(waitPath)) {
  27. doSomething();
  28. }
  29. } catch (Exception e) {
  30. e.printStackTrace();
  31. }
  32. }
  33. });
  34. // 等待连接建立
  35. latch.await();
  36. // 创建子节点
  37. thisPath = zk.create("/" + groupNode + "/" + subNode, null, Ids.OPEN_ACL_UNSAFE,
  38. CreateMode.EPHEMERAL_SEQUENTIAL);
  39. // wait一小会, 让结果更清晰一些
  40. Thread.sleep(10);
  41. // 注意, 没有必要监听"/locks"的子节点的变化情况
  42. List<String> childrenNodes = zk.getChildren("/" + groupNode, false);
  43. // 列表中只有一个子节点, 那肯定就是thisPath, 说明client获得锁
  44. if (childrenNodes.size() == 1) {
  45. doSomething();
  46. } else {
  47. String thisNode = thisPath.substring(("/" + groupNode + "/").length());
  48. // 排序
  49. Collections.sort(childrenNodes);
  50. int index = childrenNodes.indexOf(thisNode);
  51. if (index == -1) {
  52. // never happened
  53. } else if (index == 0) {
  54. // inddx == 0, 说明thisNode在列表中最小, 当前client获得锁
  55. doSomething();
  56. } else {
  57. // 获得排名比thisPath前1位的节点
  58. this.waitPath = "/" + groupNode + "/" + childrenNodes.get(index - 1);
  59. // 在waitPath上注册监听器, 当waitPath被删除时, zookeeper会回调监听器的process方法
  60. zk.getData(waitPath, true, new Stat());
  61. }
  62. }
  63. }
  64. private void doSomething() throws Exception {
  65. try {
  66. System.out.println("gain lock: " + thisPath);
  67. Thread.sleep(2000);
  68. // do something
  69. } finally {
  70. System.out.println("finished: " + thisPath);
  71. // 将thisPath删除, 监听thisPath的client将获得通知
  72. // 相当于释放锁
  73. zk.delete(this.thisPath, -1);
  74. }
  75. }
  76. public static void main(String[] args) throws Exception {
  77. for (int i = 0; i < 10; i++) {
  78. new Thread() {
  79. public void run() {
  80. try {
  81. DistributedClient dl = new DistributedClient();
  82. dl.connectZookeeper();
  83. } catch (Exception e) {
  84. e.printStackTrace();
  85. }
  86. }
  87. }.start();
  88. }
  89. Thread.sleep(Long.MAX_VALUE);
  90. }
  91. }

思考

思维缜密的朋友可能会想到, 上述的方案并不安全. 假设某个client在获得锁之前挂掉了, 由于client创建的节点是ephemeral类型的, 因此这个节点也会被删除, 从而导致排在这个client之后的client提前获得了锁. 此时会存在多个client同时访问共享资源.
如何解决这个问题呢? 可以在接到waitPath的删除通知的时候, 进行一次确认, 确认当前的thisPath是否真的是列表中最小的节点.

  1. // 发生了waitPath的删除事件
  2. if (event.getType() == EventType.NodeDeleted && event.getPath().equals(waitPath)) {
  3. // 确认thisPath是否真的是列表中的最小节点
  4. List<String> childrenNodes = zk.getChildren("/" + groupNode, false);
  5. String thisNode = thisPath.substring(("/" + groupNode + "/").length());
  6. // 排序
  7. Collections.sort(childrenNodes);
  8. int index = childrenNodes.indexOf(thisNode);
  9. if (index == 0) {
  10. // 确实是最小节点
  11. doSomething();
  12. } else {
  13. // 说明waitPath是由于出现异常而挂掉的
  14. // 更新waitPath
  15. waitPath = "/" + groupNode + "/" + childrenNodes.get(index - 1);
  16. // 重新注册监听, 并判断此时waitPath是否已删除
  17. if (zk.exists(waitPath, true) == null) {
  18. doSomething();
  19. }
  20. }
  21. }

另外, 由于thisPath和waitPath这2个成员变量会在多个线程中访问, 最好将他们声明为volatile, 以防止出现线程可见性问题.

另一种思路

下面介绍一种更简单, 但是不怎么推荐的解决方案.
每个client在getChildren的时候, 注册监听子节点的变化. 当子节点的变化通知到来时, 再一次通过getChildren获取子节点列表, 判断thisPath是否是列表中的最小节点, 如果是, 则执行资源访问逻辑.

  1. public class DistributedClient2 {
  2. // 超时时间
  3. private static final int SESSION_TIMEOUT = 5000;
  4. // zookeeper server列表
  5. private String hosts = "localhost:4180,localhost:4181,localhost:4182";
  6. private String groupNode = "locks";
  7. private String subNode = "sub";
  8. private ZooKeeper zk;
  9. // 当前client创建的子节点
  10. private volatile String thisPath;
  11. private CountDownLatch latch = new CountDownLatch(1);
  12. /**
  13. * 连接zookeeper
  14. */
  15. public void connectZookeeper() throws Exception {
  16. zk = new ZooKeeper(hosts, SESSION_TIMEOUT, new Watcher() {
  17. public void process(WatchedEvent event) {
  18. try {
  19. // 连接建立时, 打开latch, 唤醒wait在该latch上的线程
  20. if (event.getState() == KeeperState.SyncConnected) {
  21. latch.countDown();
  22. }
  23. // 子节点发生变化
  24. if (event.getType() == EventType.NodeChildrenChanged && event.getPath().equals("/" + groupNode)) {
  25. // thisPath是否是列表中的最小节点
  26. List<String> childrenNodes = zk.getChildren("/" + groupNode, true);
  27. String thisNode = thisPath.substring(("/" + groupNode + "/").length());
  28. // 排序
  29. Collections.sort(childrenNodes);
  30. if (childrenNodes.indexOf(thisNode) == 0) {
  31. doSomething();
  32. }
  33. }
  34. } catch (Exception e) {
  35. e.printStackTrace();
  36. }
  37. }
  38. });
  39. // 等待连接建立
  40. latch.await();
  41. // 创建子节点
  42. thisPath = zk.create("/" + groupNode + "/" + subNode, null, Ids.OPEN_ACL_UNSAFE,
  43. CreateMode.EPHEMERAL_SEQUENTIAL);
  44. // wait一小会, 让结果更清晰一些
  45. Thread.sleep(10);
  46. // 监听子节点的变化
  47. List<String> childrenNodes = zk.getChildren("/" + groupNode, true);
  48. // 列表中只有一个子节点, 那肯定就是thisPath, 说明client获得锁
  49. if (childrenNodes.size() == 1) {
  50. doSomething();
  51. }
  52. }
  53. /**
  54. * 共享资源的访问逻辑写在这个方法中
  55. */
  56. private void doSomething() throws Exception {
  57. try {
  58. System.out.println("gain lock: " + thisPath);
  59. Thread.sleep(2000);
  60. // do something
  61. } finally {
  62. System.out.println("finished: " + thisPath);
  63. // 将thisPath删除, 监听thisPath的client将获得通知
  64. // 相当于释放锁
  65. zk.delete(this.thisPath, -1);
  66. }
  67. }
  68. public static void main(String[] args) throws Exception {
  69. for (int i = 0; i < 10; i++) {
  70. new Thread() {
  71. public void run() {
  72. try {
  73. DistributedClient2 dl = new DistributedClient2();
  74. dl.connectZookeeper();
  75. } catch (Exception e) {
  76. e.printStackTrace();
  77. }
  78. }
  79. }.start();
  80. }
  81. Thread.sleep(Long.MAX_VALUE);
  82. }
  83. }

为什么不推荐这个方案呢? 是因为每次子节点的增加和删除都要广播给所有client, client数量不多时还看不出问题. 如果存在很多client, 那么就可能导致广播风暴--过多的广播通知阻塞了网络. 使用第一个方案, 会使得通知的数量大大下降. 当然第一个方案更复杂一些, 复杂的方案同时也意味着更容易引进bug.

 
 

ZooKeeper示例 分布式锁的更多相关文章

  1. Redis、Zookeeper实现分布式锁——原理与实践

    Redis与分布式锁的问题已经是老生常谈了,本文尝试总结一些Redis.Zookeeper实现分布式锁的常用方案,并提供一些比较好的实践思路(基于Java).不足之处,欢迎探讨. Redis分布式锁 ...

  2. zookeeper实现分布式锁服务

    A distributed lock base on zookeeper. zookeeper是hadoop下面的一个子项目, 用来协调跟hadoop相关的一些分布式的框架, 如hadoop, hiv ...

  3. [ZooKeeper.net] 3 ZooKeeper的分布式锁

    基于ZooKeeper的分布式锁 ZooKeeper 里实现分布式锁的基本逻辑: 1.zookeeper中创建一个根节点(Locks),用于后续各个客户端的锁操作. 2.想要获取锁的client都在L ...

  4. 基于 Zookeeper 的分布式锁实现

    1. 背景 最近在学习 Zookeeper,在刚开始接触 Zookeeper 的时候,完全不知道 Zookeeper 有什么用.且很多资料都是将 Zookeeper 描述成一个“类 Unix/Linu ...

  5. zookeeper的分布式锁

    实现分布式锁目前有三种流行方案,分别为基于数据库.Redis.Zookeeper的方案,其中前两种方案网络上有很多资料可以参考,本文不做展开.我们来看下使用Zookeeper如何实现分布式锁. 什么是 ...

  6. zookeeper 实现分布式锁安全用法

    zookeeper 实现分布式锁安全用法 标签: zookeeper sessionExpire connectionLoss 分布式锁 背景 ConnectionLoss 链接丢失 SessionE ...

  7. 基于Zookeeper的分布式锁

    实现分布式锁目前有三种流行方案,分别为基于数据库.Redis.Zookeeper的方案,其中前两种方案网络上有很多资料可以参考,本文不做展开.我们来看下使用Zookeeper如何实现分布式锁. 什么是 ...

  8. 转载 [ZooKeeper.net] 3 ZooKeeper的分布式锁

    [ZooKeeper.net] 3 ZooKeeper的分布式锁   基于ZooKeeper的分布式锁  源码分享:http://pan.baidu.com/s/1miQCDKk ZooKeeper ...

  9. Redis与Zookeeper实现分布式锁的区别

    Redis实现分布式锁 1.根据lockKey区进行setnx(set not exist,如果key值为空,则正常设置,返回1,否则不会进行设置并返回0)操作,如果设置成功,表示已经获得锁,否则并没 ...

随机推荐

  1. 【RS】BPR:Bayesian Personalized Ranking from Implicit Feedback - BPR:利用隐反馈的贝叶斯个性化排序

    [论文标题]BPR:Bayesian Personalized Ranking from Implicit Feedback (2012,Published by ACM Press) [论文作者]S ...

  2. JavaScript RegExp Object 正则表达式入门

    什么是 RegExp? RegExp 是regular expression的缩写. RegExp 对象表示正则表达式,它是对字符串执行模式匹配的强大工具. 当您检索某个文本时,可以使用一种模式来描述 ...

  3. 关于JAVA路径 问题

    1.基本概念的理解  绝对路径:绝对路径就是你的主页上的文件或目录在硬盘上真正的路径,(URL和物理路径)例如: C:\xyz\test.txt 代表了test.txt文件的绝对路径.http://w ...

  4. 【LeetCode】221. Maximal Square

    Maximal Square Given a 2D binary matrix filled with 0's and 1's, find the largest square containing ...

  5. 【DeepLearning】Exercise:Sparse Autoencoder

    Exercise:Sparse Autoencoder 习题的链接:Exercise:Sparse Autoencoder 注意点: 1.训练样本像素值需要归一化. 因为输出层的激活函数是logist ...

  6. LNMP分离式部署实例[转]

    很多人在练习部署LNMP环境的时候,大都数是部署在同一个虚拟机上面的.但是实际工作中,我们一般都是分离部署的. 今天我就用3台虚拟机,部署下LNMP环境.以供参考! 网络拓扑图: 首先准备3台虚拟机: ...

  7. 树莓派进阶之路 (029) - 语音识别模块 LD3320(原创)

    近几天听朋友有说到LD3320 语音模块,刚好身边有块树莓派3,就在某宝上买了块自带mcu的LD3320 . 准备: 树莓派一个(配置了wiringPi开发环境的详情见本人博客:树莓派进阶之路 (00 ...

  8. 使用SQL Server发送邮件时遇到的诡异事件

    最近公司要实现一个邮件群发的功能,因此设计时就考虑用SQL Server的邮件发送功能直接推送邮件算了. 可是在实现的过程中,邮件内容中有一个表格的内容要展现,于是就编排了一个表格来实现. 具体实现如 ...

  9. android studio 修改gradle引用本地文件

    如何使用本地gradle修改gradle-wrapper.properties文件下的 distributionUrl=file:///Volumes/MAC-WORK/download/gradle ...

  10. RocketMQ os.sh 系统优化(CentOS)

    贴出源码中的优化脚本先: #!/bin/sh # # Execute Only Once # echo 'vm.overcommit_memory=1' >> /etc/sysctl.co ...