package pers.machi.ZookeeperDistributedLock;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;
import pers.machi.leetcode.DataMonitor;
import java.io.IOException;
public class Executor implements Runnable {
private Object lock = new Object();
String name;
public DistributedLock dl;
ZooKeeper zk;
public Executor(String name,String hostPort) throws IOException, KeeperException, InterruptedException {
this.name=name;
zk = new ZooKeeper(hostPort, 3000, null);
dl = new DistributedLock(zk, "/lock", this);
}
public void doJob() {
synchronized (lock) {
try {
int c =0;
while (c<5) {
System.out.println(name+" "+ this.dl.myLock+" "+"i am working");
Thread.sleep(1000);
c++;
}
zk.delete(dl.myLock,-1);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (KeeperException e) {
e.printStackTrace();
}
}
}
@Override
public void run() {
try {
dl.getLockAndExecute();
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package pers.machi.ZookeeperDistributedLock;
import org.apache.zookeeper.*;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.PriorityQueue;
import java.util.function.Consumer;
import static org.apache.zookeeper.CreateMode.EPHEMERAL_SEQUENTIAL;
public class DistributedLock implements Watcher {
ZooKeeper zk;
String lockNode;
Executor executor;
String myLock;
public DistributedLock(ZooKeeper zk, String lockNode, Executor executor) throws KeeperException, InterruptedException {
this.zk = zk;
this.lockNode = lockNode;
this.executor = executor;
myLock = zk.create(lockNode + "/" + "id", executor.toString().getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, EPHEMERAL_SEQUENTIAL);
}
public String getNextLowestChildren() throws KeeperException, InterruptedException {
List<String> children = zk.getChildren(lockNode, false);
PriorityQueue<String> pq = new PriorityQueue<>((o1, o2) -> -o1.compareTo(o2));
for (String node : children) {
if ((lockNode+"/"+node).compareTo(myLock) < 0)
pq.add(node);
}
return pq.poll();
}
public void getLockAndExecute() throws KeeperException, InterruptedException {
String children = getNextLowestChildren();
System.out.println(executor.name + "的前一个节点:" + children);
if (getNextLowestChildren() == null) {
executor.doJob();
} else
zk.exists(lockNode + "/" + getNextLowestChildren(), this);
}
public void process(WatchedEvent watchedEvent) {
executor.doJob();
}
}
在这里插入代码片