在zookeeper集群客户端创建/servers节点
在springboot项目中创建类:DistributeServer:
编写连接zookeeper、注册服务器到zookeeper上,以及业务逻辑
public class DistributeServer {
private String connectString = "192.168.59.128:2181,192.168.59.129:2181,192.168.59.130:2181";
private int sessionTimeout = 2000;
private ZooKeeper zk;
public static void main(String[] args) throws IOException,KeeperException,InterruptedException{
DistributeServer server = new DistributeServer();
//1.获取zk连接
server.getConnect();
//2.注册服务器到zk集群
server.regist(args[0]);
//3.启动业务逻辑(睡觉)
server.business();
}
private void business() throws InterruptedException{
//模拟睡眠
Thread.sleep(Long.MAX_VALUE);
}
private void regist(String hostname) throws KeeperException,InterruptedException{
//创建节点
zk.create("/servers/",hostname.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);//在servers下创建子节点,有序的持久的
System.out.println(hostname + "is online");
}
private void getConnect() throws IOException {
//连接
zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
}
});
}
}
新建DistributeClient类进行监听:
public class DistributeClient {
private String connectString = "192.168.59.128:2181,192.168.59.129:2181,192.168.59.130:2181";
private int sessionTimeout = 2000;
private ZooKeeper zk;
public static void main(String[] args) throws IOException,KeeperException,InterruptedException{
DistributeClient client = new DistributeClient();
//1.获取zk连接
client.getConnect();
//2.监听/servers下面的子节点的增加和删除
client.getServerList();
//3.业务逻辑(睡觉)
client.business();
}
private void getServerList() throws KeeperException,InterruptedException{
List<String> children = zk.getChildren("/servers", true);
ArrayList<String> servers = new ArrayList<>();
for (String child:children){//遍历节点取出名称
byte[] data = zk.getData("/servers/" + child, false, null);
servers.add(new String(data));//加入集合
}
//打印
System.out.println(servers);
}
private void business() throws InterruptedException{
//模拟睡眠
Thread.sleep(Long.MAX_VALUE);
}
private void getConnect() throws IOException {
//连接
zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
System.out.println("====================");//持续监听
try {
getServerList();
}catch (KeeperException e){
e.printStackTrace();
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println("=====================");
}
});
}
}
启动监听类:
第一次监听内部没有数据,
在服务器客户端添加数据:
控制台日志信息实时更新:
到此,客户端的实时上下线监听实现,再来看服务端的
启动DistributeServer类
点击配置修改hostname:
修改完毕运行:
Server上出现已经上线通知,接下来查看client日志:
显示出现该节点,该节点出现原始是server的regist方法有创建子节点的方法,而client中监听这/servers下得子节点的变化,从而实现实时监听上下线。
当我们修改hostname为hadoop130的时候,在启动:
Server端:
Client端: 130会上线,随后129下线