🔰 学习视频 🔰
【尚硅谷】2021新版Zookeeper 3.5.7版本教程
集数:20—23
🔰 学习笔记 🔰
一、需求分析
某分布式系统中,主节点可以有多台,可以动态上下线,任意一台客户端都能实时感知到主节点服务器的上下线。
二、具体实现
2.1 代码
步骤1:先在集群上创建/servers
节点
create /servers "servers"
步骤2:编写模拟分布式服务器端代码
public class DistributeServer {
private String connectString = "192.168.150.101:2181";
private int sessionTimeout = 10000;
private ZooKeeper zooKeeper;
public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
DistributeServer server = new DistributeServer();
// 1 获取zk连接
server.getConnect();
// 2 注册服务器到zk集群
server.regist(args[0]);
// 3 启动业务逻辑(睡觉)
server.businesss();
}
private void businesss() throws InterruptedException {
Thread.sleep(Long.MAX_VALUE);
}
private void regist(String hostname) throws InterruptedException, KeeperException {
String create = zooKeeper.create("/servers/" + hostname, hostname.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
System.out.println(hostname + " is online!");
}
private void getConnect() throws IOException {
zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
}
});
}
}
步骤3:编写模拟分布式客户端代码
public class DistributeClient {
private String connectString = "192.168.150.101:2181";
private int sessionTimeout = 10000;
private ZooKeeper zooKeeper;
public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
DistributeClient client = new DistributeClient();
// 1 获取连接
client.getConnect();
// 2 监听/servers下面子节点的增加和删除
client.getServerList();
// 3 业务逻辑(睡觉)
client.businesss();
}
private void getServerList() throws InterruptedException, KeeperException {
List<String> children = zooKeeper.getChildren("/servers", true);
ArrayList<String> servers = new ArrayList<>();
for (String child : children) {
byte[] data = zooKeeper.getData("/servers/" + child, false, null);
servers.add(new String(data));
}
System.out.println(servers);
}
private void businesss() throws InterruptedException {
Thread.sleep(Long.MAX_VALUE);
}
private void getConnect() throws IOException {
zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
// 调用getServerList,可以保证持续监听
try {
getServerList();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (KeeperException e) {
e.printStackTrace();
}
}
});
}
}
2.2 测试
步骤1:运行客户端代码DistributeClient
步骤2:启动zk服务器的命令行,测试客户端能否监控到zk节点的变化
zk命令行:
[zk: localhost:2181(CONNECTED) 11] create /servers/server1 "server1"
Created /servers/server1
[zk: localhost:2181(CONNECTED) 12] create /servers/server2 "server2"
Created /servers/server2
Idea运行的客户端输出
# 运行时输出
[]
[]
# create /servers/server1 "server1" 后输出
[server1]
# create /servers/server2 "server2" 后输出
[server2, server1]
可证明客户端代码没问题。
步骤3:带参数运行模拟的服务端程序
首先要设置参数
此时运行代码。
模拟的服务端控制台打印:
server3 is online!
模拟的客户端控制台打印:
[server3, server2, server1]