1、使用ZooKeeper实现Java跨JVM的分布式锁java
2、使用ZooKeeper实现Java跨JVM的分布式锁(优化构思)node
3、使用ZooKeeper实现Java跨JVM的分布式锁(读写锁)apache
说明:本文是使用Curator框架进行讲解及演示,Curator是对Zookeeper客户端的一个封装,由于Zookeeper的客户端实现偏底层,若是想要实现锁或其余功能都须要本身封装,实现一些简单的功能还能够,若是想要实现锁这种高并发下的东西,不建议本身封装,除非你自信你写的东西比国外大神写的还好~ 若是是研究学习到是能够本身写一下,同时也能够看看开源的代码,那里面仍是有不少值得学习的东西。安全
Zookeeper版本为 Release 3.4.8(stable)服务器
Curator版本为2.9.1session
- <dependency>
- <groupId>org.apache.zookeeper</groupId>
- <artifactId>zookeeper</artifactId>
- <version>3.4.8</version>
- </dependency>
-
- <dependency>
- <groupId>org.apache.curator</groupId>
- <artifactId>curator-recipes</artifactId>
- <version>2.9.1</version>
- </dependency>
-
- <dependency>
- <groupId>org.apache.curator</groupId>
- <artifactId>curator-client</artifactId>
- <version>2.9.1</version>
- </dependency>
锁原理:并发
一、首先要建立一个锁的根节点,好比/mylock。app
二、想要获取锁的客户端在锁的根节点下面建立znode,做为/mylock的子节点,节点的类型要选择CreateMode.PERSISTENT_SEQUENTIAL,节点的名字最好用uuid(至于为何用uuid我后面会讲,先说一下~若是不这么作在某种状况下会发生死锁,这一点我看了不少国内朋友本身的实现,都没有考虑到这一层,这也是我为何不建议你们本身去封装这种锁,由于它确实很复杂),假设目前同时有3个客户端想要得到锁,那么/mylock下的目录应该是这个样子的。框架
xxx-lock-0000000001,xxx-lock-0000000002,xxx-lock-0000000003dom
xxx为uuid , 0000000001,0000000002,0000000003 是zook服务端自动生成的自增数字。
三、当前客户端经过getChildren(/mylock)获取全部子节点列表并根据自增数字排序,而后判断一下本身建立的节点的顺序是否是在列表当中最小的,若是是 那么获取到锁,若是不是,那么获取本身的前一个节点,并设置监听这个节点的变化,当节点变化时从新执行步骤3 直到本身是编号最小的一个为止。
举例:假设当前客户端建立的节点是0000000002,由于它的编号不是最小的,因此获取不到锁,那么它就找到它前面的一个节点0000000001 并对它设置监听。
四、释放锁,当前得到锁的客户端在操做完成后删除本身建立的节点,这样会激发zook的事件给其它客户端知道,这样其它客户端会从新执行(步骤3)。
举例:加入客户端0000000001获取到锁,而后客户端0000000002加入进来获取锁,发现本身不是编号最小的,那么它会监听它前面节点的事件(0000000001的事件)而后执行步骤(3),当客户端0000000001操做完成后删除本身的节点,这时zook服务端会发送事件,这时客户端0000000002会接收到该事件,而后重复步骤3直到获取到锁)
上面的步骤实现了一个有序锁,也就是先进入等待锁的客户端在锁可用时先得到锁。
若是想要实现一个随机锁,那么只须要把PERSISTENT_SEQUENTIAL换成一个随机数便可。
简单示例:
- package com.framework.code.demo.zook;
-
- import org.apache.curator.RetryPolicy;
- import org.apache.curator.framework.CuratorFramework;
- import org.apache.curator.framework.CuratorFrameworkFactory;
- import org.apache.curator.framework.recipes.locks.InterProcessMutex;
- import org.apache.curator.retry.ExponentialBackoffRetry;
-
- public class CuratorDemo {
-
- public static void main(String[] args) throws Exception {
-
-
- RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
-
- CuratorFramework client = CuratorFrameworkFactory.newClient("192.168.1.18:2181", retryPolicy);
-
- client.start();
-
-
- final InterProcessMutex lock = new InterProcessMutex(client, "/mylock");
- try {
-
- lock.acquire();
- System.out.println("已经获取到锁");
- Thread.sleep(10000);
- } catch (Exception e) {
- e.printStackTrace();
- }
- finally{
-
- lock.release();
- }
-
- Thread.sleep(10000);
-
- client.close();
- }
-
- }
上面代码再获取锁的地方暂停了10秒钟,咱们使用zook的客户端去查看目录的建立状况,因为我前面已经作了几回测试,因此序号是从12开始的。

模拟多个客户端(也能够认为是多个JVM):
如今把上面的代码改造一下放入到线程中去执行,模拟多个客户端测试。
- public class CuratorDemo {
-
- public static void main(String[] args) throws Exception {
- for (int i = 0; i < 10; i++) {
-
- Jvmlock jl = new Jvmlock(i);
- new Thread(jl).start();
-
- Thread.sleep(300);
- }
- }
-
- public static class Jvmlock implements Runnable{
-
- private int num;
- public Jvmlock(int num) {
- this.num = num;
- }
-
- @Override
- public void run() {
- RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000,3);
- CuratorFramework client = CuratorFrameworkFactory
- .newClient("192.168.142.128:2181", retryPolicy);
- client.start();
-
- InterProcessMutex lock = new InterProcessMutex(client,
- "/mylock");
- try {
- System.out.println("我是第" + num + "号线程,我开始获取锁");
- lock.acquire();
- System.out.println("我是第" + num + "号线程,我已经获取锁");
- Thread.sleep(10000);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- lock.release();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- client.close();
- }
- }
-
- }
经过客户端软件咱们能够看到10个申请锁的节点已经被建立出来了。

看一下打印结果,先申请获取锁的线程在锁可用时最早获取到锁,由于他们申请锁时建立节点的顺序号是递增的,先申请锁的客户端建立的节点编号最小,因此先获取到锁
- 我是第0号线程,我开始获取锁
- 我是第0号线程,我已经获取锁
- 我是第1号线程,我开始获取锁
- 我是第2号线程,我开始获取锁
- 我是第3号线程,我开始获取锁
- 我是第4号线程,我开始获取锁
- 我是第5号线程,我开始获取锁
- 我是第6号线程,我开始获取锁
- 我是第7号线程,我开始获取锁
- 我是第8号线程,我开始获取锁
- 我是第9号线程,我开始获取锁
- 我是第1号线程,我已经获取锁
- 我是第2号线程,我已经获取锁
- 我是第3号线程,我已经获取锁
- 我是第4号线程,我已经获取锁
- 我是第5号线程,我已经获取锁
- 我是第6号线程,我已经获取锁
- 我是第7号线程,我已经获取锁
- 我是第8号线程,我已经获取锁
- 我是第9号线程,我已经获取锁
为何节点的名称要加上uuid,这是框架的英文解释。
It turns out there is an edge case that exists when creating sequential-ephemeral nodes. The creation can succeed on the server, but the server can crash before the created node name is returned to the client. However, the ZK session is still valid so the ephemeral node is not deleted. Thus, there is no way for the client to determine what node was created for them.
Even without sequential-ephemeral, however, the create can succeed on the sever but the client (for various reasons) will not know it.
Putting the create builder into protection mode works around this. The name of the node that is created is prefixed with a GUID. If node creation fails the normal retry mechanism will occur. On the retry, the parent path is first searched for a node that has the GUID in it. If that node is found, it is assumed to be the lost node that was successfully created on the first try and is returned to the caller.
就是说 当客户端建立了一个节点,这个建立的过程在zook的服务器端已经成功了,可是在将节点的路径返回给客户端以前服务器端挂了, 由于客户端的session仍是有效的,因此这个节点不会删除, 这样客户端就不知道哪一个节点是它建立的。
当客户端发生建立失败的时候,会进行重试,若是这个时候zook已经恢复可用,那么客户端会查询服务器端全部子节点,而后经过和本身建立的uuid对比,若是找到了,说明这个节点是它以前建立的,那么久直接使用它,否则这个节点就会成为一个死节点,致使死锁。
实现非公平锁:
重写建立节点的方法,
- package com.framework.code.demo.zook.lock;
-
- import org.apache.curator.framework.CuratorFramework;
- import org.apache.curator.framework.recipes.locks.StandardLockInternalsDriver;
- import org.apache.zookeeper.CreateMode;
-
- public class NoFairLockDriver extends StandardLockInternalsDriver {
-
-
- private int numLength;
- private static int DEFAULT_LENGTH = 5;
-
- public NoFairLockDriver() {
- this(DEFAULT_LENGTH);
- }
-
- public NoFairLockDriver(int numLength) {
- this.numLength = numLength;
- }
-
- @Override
- public String createsTheLock(CuratorFramework client, String path, byte[] lockNodeBytes) throws Exception
- {
- String newPath = path + getRandomSuffix();
- String ourPath;
- if ( lockNodeBytes != null )
- {
-
-
-
-
-
- ourPath = client.create().creatingParentContainersIfNeeded().withProtection().withMode(CreateMode.EPHEMERAL).forPath(newPath, lockNodeBytes);
-
- }
- else
- {
- ourPath = client.create().creatingParentContainersIfNeeded().withProtection().withMode(CreateMode.EPHEMERAL).forPath(newPath);
-
- }
- return ourPath;
- }
-
-
- public String getRandomSuffix() {
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < numLength; i++) {
- sb.append((int) (Math.random() * 10));
- }
- return sb.toString();
- }
-
- }
把咱们写的类注册进去:
- InterProcessMutex lock = new InterProcessMutex(client,"/mylock", new NoFairLockDriver());
仍是上面的例子,在跑一边看结果,能够看到,获取锁的顺序已是无序的了,从而实现了非公平锁。
- 我是第1号线程,我开始获取锁
- 我是第0号线程,我开始获取锁
- 我是第0号线程,我已经获取锁
- 我是第2号线程,我开始获取锁
- 我是第3号线程,我开始获取锁
- 我是第4号线程,我开始获取锁
- 我是第5号线程,我开始获取锁
- 我是第6号线程,我开始获取锁
- 我是第7号线程,我开始获取锁
- 我是第8号线程,我开始获取锁
- 我是第9号线程,我开始获取锁
- 我是第9号线程,我已经获取锁
- 我是第8号线程,我已经获取锁
- 我是第4号线程,我已经获取锁
- 我是第7号线程,我已经获取锁
- 我是第3号线程,我已经获取锁
- 我是第1号线程,我已经获取锁
- 我是第2号线程,我已经获取锁
- 我是第5号线程,我已经获取锁
- 我是第6号线程,我已经获取锁