首先创建一个maven工程,然后导入基础的需要的,导入zookeeper依赖<dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.6.3</version> </dependency>
首先先创建一个服务器端
package com.zookeeper;
import jdk.nashorn.internal.ir.debug.ClassHistogramElement;
import org.apache.zookeeper.*;
import java.io.IOException;
public class FirstServer {
String connectionString = ""; //连接到的主机
Integer sessionTimeOut = 2000;
ZooKeeper zk = null;
public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
FirstServer server = new FirstServer();
//1.获取zookeeper 连接
server.getConnection();
//2.绑定对应的节点 ---注册服务器到对应的集群
server.register(args[0]);
//3.节点的具体业务
server.business();
}
private void business() throws InterruptedException {
Thread.sleep(100);
}
private void register(String hostName) throws KeeperException, InterruptedException {
//向server下创建节点
String s = zk.create("/servers/" + hostName, hostName.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
System.out.println(hostName + "is online");
}
private void getConnection() throws IOException {
zk = new ZooKeeper(connectionString, sessionTimeOut, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
}
});
}
}
创建一个客户端
package com.zookeeper;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ZkClient {
private String connectionString = "client1:1001,client2:1002,client3:1003";
private int connectionTimeOut = 2000;
ZooKeeper zk = null;
public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
ZkClient client = new ZkClient();
//1.获取zk连接
client.getConnection();
//2.监听节点 server下节点的增删
client.getServerList();
//3.业务逻辑
client.business();
}
private void business() throws InterruptedException {
Thread.sleep(100);
}
private void getServerList() throws KeeperException, InterruptedException {
//获取节点下的所有连接数据
List<String> children = zk.getChildren("/server", true);//监听path true走初始化的节点
ArrayList<String> servers = new ArrayList<>();
for (String child : children) {
byte[] data = zk.getData("/server/" + child, false, null);//获取对应的数据 具体节点的路径,是否监听节点数据的变化,状态
servers.add(new String(data));
}
//打印
System.out.println(servers.size());
}
private void getConnection() throws IOException {
zk = new ZooKeeper(connectionString, connectionTimeOut, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
try {
//保证时刻监听,若不调用为初始则只监听第一次
getServerList();
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
然后用可视化工具增删对应服务器节点即可