经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 大数据/云/AI » Zookeeper » 查看文章
zookeeper【5】分布式锁
来源:cnblogs  作者:撸码识途  时间:2018/11/28 9:58:24  对本文有异议

我们常说的锁是单进程多线程锁,在多线程并发编程中,用于线程之间的数据同步,保护共享资源的访问。而分布式锁,指在分布式环境下,保护跨进程、跨主机、跨网络的共享资源,实现互斥访问,保证一致性。

 

架构图:

 

分布式锁获取思路
a、在获取分布式锁的时候在locker节点下创建临时顺序节点,释放锁的时候删除该临时节点。

b、客户端调用createNode方法在locker下创建临时顺序节点,然后调用getChildren(“locker”)来获取locker下面的所有子节点,注意此时不用设置任何Watcher。

c、客户端获取到所有的子节点path之后,如果发现自己创建的子节点序号最小,那么就认为该客户端获取到了锁。

d、如果发现自己创建的节点并非locker所有子节点中最小的,说明自己还没有获取到锁,此时客户端需要找到比自己小的那个节点,然后对其调用exist()方法,同时对其注册事件监听器。

e、之后,让这个被关注的节点删除,则客户端的Watcher会收到相应通知,此时再次判断自己创建的节点是否是locker子节点中序号最小的,如果是则获取到了锁,如果不是则重复以上步骤继续获取到比自己小的一个节点并注册监听。

 

实现代码:

  1. import org.I0Itec.zkclient.IZkDataListener;
  2. import org.I0Itec.zkclient.ZkClient;
  3. import org.I0Itec.zkclient.exception.ZkNoNodeException;
  4. import java.util.Collections;
  5. import java.util.Comparator;
  6. import java.util.List;
  7. import java.util.concurrent.CountDownLatch;
  8. import java.util.concurrent.TimeUnit;
  9. public class BaseDistributedLock {
  10. private final ZkClientExt client;
  11. private final String path;
  12. private final String basePath;
  13. private final String lockName;
  14. private static final Integer MAX_RETRY_COUNT = 10;
  15. public BaseDistributedLock(ZkClientExt client, String path, String lockName){
  16. this.client = client;
  17. this.basePath = path;
  18. this.path = path.concat("/").concat(lockName);
  19. this.lockName = lockName;
  20. }
  21. // 删除成功获取锁之后所创建的那个顺序节点
  22. private void deleteOurPath(String ourPath) throws Exception{
  23. client.delete(ourPath);
  24. }
  25. // 创建临时顺序节点
  26. private String createLockNode(ZkClient client, String path) throws Exception{
  27. return client.createEphemeralSequential(path, null);
  28. }
  29. // 等待比自己次小的顺序节点的删除
  30. private boolean waitToLock(long startMillis, Long millisToWait, String ourPath) throws Exception{
  31. boolean haveTheLock = false;
  32. boolean doDelete = false;
  33. try {
  34. while ( !haveTheLock ) {
  35. // 获取/locker下的经过排序的子节点列表
  36. List<String> children = getSortedChildren();
  37. // 获取刚才自己创建的那个顺序节点名
  38. String sequenceNodeName = ourPath.substring(basePath.length()+1);
  39. // 判断自己排第几个
  40. int ourIndex = children.indexOf(sequenceNodeName);
  41. if (ourIndex < 0){ // 网络抖动,获取到的子节点列表里可能已经没有自己了
  42. throw new ZkNoNodeException("节点没有找到: " + sequenceNodeName);
  43. }
  44. // 如果是第一个,代表自己已经获得了锁
  45. boolean isGetTheLock = ourIndex == 0;
  46. // 如果自己没有获得锁,则要watch比我们次小的那个节点
  47. String pathToWatch = isGetTheLock ? null : children.get(ourIndex - 1);
  48. if ( isGetTheLock ){
  49. haveTheLock = true;
  50. } else {
  51. // 订阅比自己次小顺序节点的删除事件
  52. String previousSequencePath = basePath .concat( "/" ) .concat( pathToWatch );
  53. final CountDownLatch latch = new CountDownLatch(1);
  54. final IZkDataListener previousListener = new IZkDataListener() {
  55. public void handleDataDeleted(String dataPath) throws Exception {
  56. latch.countDown(); // 删除后结束latch上的await
  57. }
  58. public void handleDataChange(String dataPath, Object data) throws Exception {
  59. // ignore
  60. }
  61. };
  62. try {
  63. //订阅次小顺序节点的删除事件,如果节点不存在会出现异常
  64. client.subscribeDataChanges(previousSequencePath, previousListener);
  65. if ( millisToWait != null ) {
  66. millisToWait -= (System.currentTimeMillis() - startMillis);
  67. startMillis = System.currentTimeMillis();
  68. if ( millisToWait <= 0 ) {
  69. doDelete = true; // timed out - delete our node
  70. break;
  71. }
  72. latch.await(millisToWait, TimeUnit.MICROSECONDS); // 在latch上await
  73. } else {
  74. latch.await(); // 在latch上await
  75. }
  76. // 结束latch上的等待后,继续while重新来过判断自己是否第一个顺序节点
  77. }
  78. catch ( ZkNoNodeException e ) {
  79. //ignore
  80. } finally {
  81. client.unsubscribeDataChanges(previousSequencePath, previousListener);
  82. }
  83. }
  84. }
  85. }
  86. catch ( Exception e ) {
  87. //发生异常需要删除节点
  88. doDelete = true;
  89. throw e;
  90. } finally {
  91. //如果需要删除节点
  92. if ( doDelete ) {
  93. deleteOurPath(ourPath);
  94. }
  95. }
  96. return haveTheLock;
  97. }
  98. private String getLockNodeNumber(String str, String lockName) {
  99. int index = str.lastIndexOf(lockName);
  100. if ( index >= 0 ) {
  101. index += lockName.length();
  102. return index <= str.length() ? str.substring(index) : "";
  103. }
  104. return str;
  105. }
  106. // 获取/locker下的经过排序的子节点列表
  107. List<String> getSortedChildren() throws Exception {
  108. try{
  109. List<String> children = client.getChildren(basePath);
  110. Collections.sort(
  111. children, new Comparator<String>() {
  112. public int compare(String lhs, String rhs) {
  113. return getLockNodeNumber(lhs, lockName).compareTo(getLockNodeNumber(rhs, lockName));
  114. }
  115. }
  116. );
  117. return children;
  118. } catch (ZkNoNodeException e){
  119. client.createPersistent(basePath, true);
  120. return getSortedChildren();
  121. }
  122. }
  123. protected void releaseLock(String lockPath) throws Exception{
  124. deleteOurPath(lockPath);
  125. }
  126. protected String attemptLock(long time, TimeUnit unit) throws Exception {
  127. final long startMillis = System.currentTimeMillis();
  128. final Long millisToWait = (unit != null) ? unit.toMillis(time) : null;
  129. String ourPath = null;
  130. boolean hasTheLock = false;
  131. boolean isDone = false;
  132. int retryCount = 0;
  133. //网络闪断需要重试一试
  134. while ( !isDone ) {
  135. isDone = true;
  136. try {
  137. // 在/locker下创建临时的顺序节点
  138. ourPath = createLockNode(client, path);
  139. // 判断自己是否获得了锁,如果没有获得那么等待直到获得锁或者超时
  140. hasTheLock = waitToLock(startMillis, millisToWait, ourPath);
  141. } catch ( ZkNoNodeException e ) { // 捕获这个异常
  142. if ( retryCount++ < MAX_RETRY_COUNT ) { // 重试指定次数
  143. isDone = false;
  144. } else {
  145. throw e;
  146. }
  147. }
  148. }
  149. if ( hasTheLock ) {
  150. return ourPath;
  151. }
  152. return null;
  153. }
  154. }
  1. import java.util.concurrent.TimeUnit;
  2. public interface DistributedLock {
  3. /*
  4. * 获取锁,如果没有得到就等待
  5. */
  6. public void acquire() throws Exception;
  7. /*
  8. * 获取锁,直到超时
  9. */
  10. public boolean acquire(long time, TimeUnit unit) throws Exception;
  11. /*
  12. * 释放锁
  13. */
  14. public void release() throws Exception;
  15. }
  1. import java.io.IOException;
  2. import java.util.concurrent.TimeUnit;
  3. public class SimpleDistributedLockMutex extends BaseDistributedLock implements
  4. DistributedLock {
  5. //锁名称前缀,成功创建的顺序节点如lock-0000000000,lock-0000000001,...
  6. private static final String LOCK_NAME = "lock-";
  7. // zookeeper中locker节点的路径
  8. private final String basePath;
  9. // 获取锁以后自己创建的那个顺序节点的路径
  10. private String ourLockPath;
  11. private boolean internalLock(long time, TimeUnit unit) throws Exception {
  12. ourLockPath = attemptLock(time, unit);
  13. return ourLockPath != null;
  14. }
  15. public SimpleDistributedLockMutex(ZkClientExt client, String basePath){
  16. super(client,basePath,LOCK_NAME);
  17. this.basePath = basePath;
  18. }
  19. // 获取锁
  20. public void acquire() throws Exception {
  21. if ( !internalLock(-1, null) ) {
  22. throw new IOException("连接丢失!在路径:'"+basePath+"'下不能获取锁!");
  23. }
  24. }
  25. // 获取锁,可以超时
  26. public boolean acquire(long time, TimeUnit unit) throws Exception {
  27. return internalLock(time, unit);
  28. }
  29. // 释放锁
  30. public void release() throws Exception {
  31. releaseLock(ourLockPath);
  32. }
  33. }
  1. import org.I0Itec.zkclient.serialize.BytesPushThroughSerializer;
  2. public class TestDistributedLock {
  3. public static void main(String[] args) {
  4. final ZkClientExt zkClientExt1 = new ZkClientExt("192.168.1.105:2181", 5000, 5000, new BytesPushThroughSerializer());
  5. final SimpleDistributedLockMutex mutex1 = new SimpleDistributedLockMutex(zkClientExt1, "/Mutex");
  6. final ZkClientExt zkClientExt2 = new ZkClientExt("192.168.1.105:2181", 5000, 5000, new BytesPushThroughSerializer());
  7. final SimpleDistributedLockMutex mutex2 = new SimpleDistributedLockMutex(zkClientExt2, "/Mutex");
  8. try {
  9. mutex1.acquire();
  10. System.out.println("Client1 locked");
  11. Thread client2Thd = new Thread(new Runnable() {
  12. public void run() {
  13. try {
  14. mutex2.acquire();
  15. System.out.println("Client2 locked");
  16. mutex2.release();
  17. System.out.println("Client2 released lock");
  18. } catch (Exception e) {
  19. e.printStackTrace();
  20. }
  21. }
  22. });
  23. client2Thd.start();
  24. Thread.sleep(5000);
  25. mutex1.release();
  26. System.out.println("Client1 released lock");
  27. client2Thd.join();
  28. } catch (Exception e) {
  29. e.printStackTrace();
  30. }
  31. }
  32. }
  1. import org.I0Itec.zkclient.ZkClient;
  2. import org.I0Itec.zkclient.serialize.ZkSerializer;
  3. import org.apache.zookeeper.data.Stat;
  4. import java.util.concurrent.Callable;
  5. public class ZkClientExt extends ZkClient {
  6. public ZkClientExt(String zkServers, int sessionTimeout, int connectionTimeout, ZkSerializer zkSerializer) {
  7. super(zkServers, sessionTimeout, connectionTimeout, zkSerializer);
  8. }
  9. @Override
  10. public void watchForData(final String path) {
  11. retryUntilConnected(new Callable<Object>() {
  12. public Object call() throws Exception {
  13. Stat stat = new Stat();
  14. _connection.readData(path, stat, true);
  15. return null;
  16. }
  17. });
  18. }
  19. }

 

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号