比如说“进程 1”在使用该资源的时候,会先去获得锁,“进程 1”获得锁以后会对该资源保持独占,这样其他进程就无法访问该资源,“进程 1”用完该资源以后就将锁释放掉,让其他进程来获得锁,那么通过这个锁机制,我们就能就能保证了分布式系统中多个进程能够有序的访问该临界资源。那么我们把这个分布式环境下的这个锁叫做分布式锁。
1)连接上zookeeper集群;
2)判断根节点是否存在,不存在则需要创建;
3)对zookeeper进行加锁;
4)在根目录下创建对应的临时带序号节点;
5)判断节点是否是最小的序号节点,如果是,获取到锁,不是,监听前一个结点;
6)对zookeeper集群解锁,即删除节点。
public class DistributedLock {
private final String connectString = "zookeeper101:2181,zookeeper102:2181,zookeeper103:2181";
private final int sessionTimeout = 2000;
private final ZooKeeper zk;
private CountDownLatch connectLatch = new CountDownLatch(1);
private CountDownLatch waitLatch = new CountDownLatch(1);
private String waitPath;
private String currentNode;
public DistributedLock() throws IOException, InterruptedException, KeeperException {
//获取连接
zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
public void process(WatchedEvent watchedEvent) {
//connectLatch 如果连接上zk 可以释放
if (watchedEvent.getState() == Event.KeeperState.SyncConnected){
connectLatch.countDown();
}
//waitLatch 需要释放
if (watchedEvent.getType() == Event.EventType.NodeDeleted && watchedEvent.getPath().equals(waitPath)){
waitLatch.countDown();
}
}
});
//等待zk正常连接后,往下走程序
connectLatch.await();
//判断根节点/locks是否存在,不存在就创建
Stat stat = zk.exists("/locks", false);
if (stat == null){
//创建一下根节点
zk.create("/locks","locks".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
}
}
//对zk 加锁
public void zkLock(){
//创建临时带序号节点
try {
currentNode = zk.create("/locks/" + "seq-", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
//判断创建的节点是否是最小的带序号节点
//如果是则获取到锁,不是则要监听这个节点的前一个节点
List<String> children = zk.getChildren("/locks", false);
//如果children只有一个值,那就直接获取锁,如果有多个节点,需要判断谁最小
if (children.size() == 1){
return;
}else {
Collections.sort(children);
//获取节点名称 seq-000000
String thisNode = currentNode.substring("/locks/".length());
//通过seq-000000获取该节点在children集合的位置
int index = children.indexOf(thisNode);
//判断
if (index == -1){
System.out.println("数据异常");
}else if (index == 0){
//就一个节点,可以获取锁了
return;
}else{
//需要监听它前一个结点
waitPath = "/locks/"+children.get(index - 1);
zk.getData(waitPath,true,null);
//等待监听
waitLatch.await();
return;
}
}
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//解锁
public void unZkLock(){
//删除节点
try {
zk.delete(currentNode,-1);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (KeeperException e) {
e.printStackTrace();
}
}
}
public class DistributedTest {
public static void main(String[] args) throws InterruptedException, IOException, KeeperException {
final DistributedLock lock1 = new DistributedLock();
final DistributedLock lock2 = new DistributedLock();
new Thread(new Runnable() {
public void run() {
try {
lock1.zkLock();
System.out.println("线程1 启动,获取到锁");
Thread.sleep(5 * 1000);
lock1.unZkLock();
System.out.println("线程1 释放锁");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
public void run() {
try {
lock2.zkLock();
System.out.println("线程2 启动,获取到锁");
Thread.sleep(5000);
lock2.unZkLock();
System.out.println("线程2 释放锁");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
1)会话连接时异步的,需要自己去处理。比如使用CountDownLatch;
2)Watch需要重复注册,不然就不能生效;
3)开发的复杂性还是比较高的;
4)不支持多节点删除和创建,需要自己去递归。
详情可以查看官方文档:https://curator.apache.org/
1)在pom.xml导入依赖:
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-framework</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-client</artifactId>
<version>4.3.0</version>
</dependency>
2)代码实现:
public class CuratorLockTest {
public static void main(String[] args) {
//创建分布式锁1
final InterProcessMutex lock1 = new InterProcessMutex(getCuratorFramework(), "/locks");
//创建分布式锁2
final InterProcessMutex lock2 = new InterProcessMutex(getCuratorFramework(), "/locks");
new Thread(new Runnable() {
public void run() {
try {
lock1.acquire();
System.out.println("线程1 获取到锁");
lock1.acquire();
System.out.println("线程1再次获取到锁");
Thread.sleep(5 * 1000);
lock1.release();
System.out.println("线程1 释放锁");
lock1.release();
System.out.println("线程1 再次释放锁");
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
public void run() {
try {
lock2.acquire();
System.out.println("线程2 获取到锁");
lock2.acquire();
System.out.println("线程2再次获取到锁");
Thread.sleep(5 * 1000);
lock2.release();
System.out.println("线程2 释放锁");
lock2.release();
System.out.println("线程2 再次释放锁");
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
private static CuratorFramework getCuratorFramework() {
ExponentialBackoffRetry policy = new ExponentialBackoffRetry(3000, 3);
CuratorFramework client = CuratorFrameworkFactory.builder().connectString("zookeeper101:2181,zookeeper102:2181,zookeeper103:2181")
.connectionTimeoutMs(2000)
.sessionTimeoutMs(2000)
.retryPolicy(policy).build();
//启动客户端
client.start();
System.out.println("Zookeeper 启动成功");
return client;
}
}