在上一篇中,我们讲了使用ZooKeeper来实现分布式作业调度系统的原理,链接为:ZooKeeper完全解析(四) 使用ZooKeeper实现分布式作业调度系统之实现原理 ,这一篇中,我们将会讲使用Java实现的一些细节:
需要注意的是,这个实现还是一个基础实现,还有一些细节需要完善。
一、成为主节点:
在实现的时候,我把 slave 节点与 master 节点都抽象成 ZooNode 节点,每一个节点都可能成为 master 节点,区别在于谁先创建了 master 节点。如果创建成功,那么这个节点就执行 master 节点相关的任务,如果创建失败,就执行 slave 节点相关的任务。
public class ZooNode {
private ZooKeeper zooKeeper;
private String masterId;
public boolean isMaster;
private ZooRole zooRole;
public ZooNode() {
this.zooKeeper = ZooService.getZooKeeper();
if (this.zooKeeper == null) {
throw new NullPointerException();
}
}
/**
* 成为主节点
*/
public void createMaster() throws InterruptedException{
Random random = new Random();
String randomMasterId = Integer.toHexString(random.nextInt()) ;