需求
某分布式系统中,主节点可以有多台,可以动态上下线,任意一台客户端都能实时感知到主节点服务器的上下线。
设计
实现
public class distributeServer {
public static void main(String[] args) throws Exception {
distributeServer server = new distributeServer();
// 1 连接zookeeper集群
server.getConnect();
// 2 注册节点
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 {
String path = zkClient.create("/servers/server", hostname.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
System.out.println(hostname +"is online ");
}
private String connectString = "192.168.0.201:2181";
private int sessionTimeout = 2000;
private ZooKeeper zkClient;
private void getConnect() throws IOException {
zkClient = new ZooKeeper(connectString , sessionTimeout , new Watcher() {
@Override
public void process(WatchedEvent event) {
try {
getChlidren();
} catch (KeeperException e) {
e.printstacktrace();
} catch (InterruptedException e) {
e.printstacktrace();
}
}
});
}
private void getChlidren() throws KeeperException, InterruptedException {
List<String> children = zkClient.getChildren("/servers", true);
// 存储服务器节点主机名称集合
ArrayList<String> hosts = new ArrayList<>();
for (String child : children) {
byte[] data = zkClient.getData("/servers/"+child, false, null);
hosts.add(new String(data));
}
// 将所有在线主机名称打印到控制台
System.out.println(hosts);
}
}
预期结果
192.168.0.103is online
[192.168.0.105, 192.168.0.103]
[192.168.0.105, 192.168.0.201, 192.168.0.103]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。