首先创建一个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();
server.getConnection();
server.register(args[0]);
server.business();
}
private void business() throws InterruptedException {
Thread.sleep(100);
}
private void register(String hostName) throws KeeperException, InterruptedException {
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();
client.getConnection();
client.getServerList();
client.business();
}
private void business() throws InterruptedException {
Thread.sleep(100);
}
private void getServerList() throws KeeperException, InterruptedException {
List<String> children = zk.getChildren("/server", 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();
}
}
});
}
}
然后用可视化工具增删对应服务器节点即可
|