package com.hikvision.mes.service.system.service.util;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
public class WatchCallBack implements Watcher,AsyncCallback.StringCallback,AsyncCallback.Children2Callback,AsyncCallback.StatCallback{
ZooKeeper zk ;
String threadName;
String pathName;
CountDownLatch cc = new CountDownLatch(1);
public String getPathName() {
return pathName;
}
public void setPathName(String pathName) {
this.pathName = pathName;
}
public String getThreadName() {
return threadName;
}
public void setThreadName(String threadName) {
this.threadName = threadName;
}
public ZooKeeper getZk() {
return zk;
}
public void setZk(ZooKeeper zk) {
this.zk = zk;
}
public void tryLock(){
try {
System.out.println("threadName=="+threadName);
zk.create("/zookeeper",threadName.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL, this,"abc");
cc.await();
} catch (Exception e) {
e.printStackTrace();
}
}
public void unLock(){
try {
zk.delete(pathName,-1);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void process(WatchedEvent event) {
switch (event.getType()) {
case None:
break;
case NodeCreated:
break;
case NodeDeleted:
zk.getChildren("/",false, this,"sdf");
break;
case NodeDataChanged:
break;
case NodeChildrenChanged:
break;
}
}
@Override
public void processResult(int rc, String path, Object ctx, String name) {
if(name != null){
System.out.println("pathName=="+name);
pathName = name;
zk.getChildren("/",false,this,"sdf");
}
}
@Override
public void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) {
//排序一下然后获取第一个注册的节点
Collections.sort(children);
int i = children.indexOf(pathName.substring(1));
if( i==0 ){
cc.countDown();
}else {
zk.exists("/"+children.get(i-1),this, this,"sdf");
}
}
@Override
public void processResult(int rc, String path, Object ctx, Stat stat) {
}
}
zookeeper分布式锁
最新推荐文章于 2023-07-02 23:37:55 发布