需求
某分布式系统中,主节点可以有多台,可以动态上下线,任意一台客户端都能实时感知到主节点服务器的上下线。
思路- 创建客户端与服务端
- 启动client端 监听
- 启动server端 注册
- 当server端 发生上下线
- client端都能感知到
第一步:先在集群上创建/servers节点
create /servers "servers"
Created /servers
第二步:服务器端代码
public class DistributeServer {
private static String connectString = "hcmaster:2181,hcslave1:2181,hcslave2:2181";
private static int sessionTimeout = 2000;
private ZooKeeper zk = null;
private String parentNode = "/servers";
// 创建到zk的客户端连接
public void getConnect() throws IOException {
zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent event) {
if (event.getState() == Event.KeeperState.SyncConnected) {
System.out.println("Server端连接成功!");
}
}
});
}
// 注册服务器(创建一个临时序列节点)
public void registServer(String hostname) throws Exception {
String create = zk.create(parentNode + "/server", hostname.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
System.out.println(hostname + " is online " + create);
}
// 业务功能
public void business(String hostname) throws Exception {
System.out.println(hostname + " is working ...");
Thread.sleep(Long.MAX_VALUE);//保证进程不结束
}
public static void main(String[] args) throws Exception {
System.out.println("请输入服务器的名字");
String hostname= new Scanner(System.in).next();
// 1获取zk连接
DistributeServer server = new DistributeServer();
server.getConnect();
// 2 利用zk连接注册服务器信息
server.registServer(hostname);
// 3 启动业务功能
server.business(hostname);
}
}
第三步:客户端代码
public class DistributeClient {
private static String connectString = "hcmaster:2181,hcslave1:2181,hcslave2:2181";
private static int sessionTimeout = 20000;
private ZooKeeper zk = null;
private String parentNode = "/servers";
// 创建到zk的客户端连接
public void getConnect() throws IOException {
zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent event) {
if (event.getState() == Event.KeeperState.SyncConnected) {
System.out.println("Client 端连接成功!");
}
try { // 再次启动监听
getServerList();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
// 获取服务器列表信息
public void getServerList() throws Exception {
// 1获取服务器子节点信息,并且对父节点进行监听
List children = zk.getChildren(parentNode, true);
// 2存储服务器信息列表
ArrayList servers = new ArrayList();
// 3遍历所有节点,获取节点中的主机名称信息
for (String child : children) {
byte[] data = zk.getData(parentNode + "/" + child, false, null);
servers.add(new String(data));
}
// 4打印服务器列表信息
System.out.println(servers);
}
// 业务功能
public void business() throws Exception {
System.out.println("client is working ...");
Thread.sleep(Long.MAX_VALUE);
}
public static void main(String[] args) throws Exception {
// 1获取zk连接
DistributeClient client = new DistributeClient();
client.getConnect();
// 2获取servers的子节点信息,从中获取服务器信息列表
client.getServerList();
// 3业务进程启动
client.business();
}
}
第四步:运行测试
- 通过Shell方式创建节点servers,如下图所示:
- 启动DistributeClient:
- 在Shell中创建节点并在Intellij中查看对应的结果:
- 启动DistributeServer:
5.查看DistributeClient: