1、Code -> GitHub
https://github.com/liufengji/zookeeper_code.git
2、需求
某分布式系统中,主节点可以有多台,可以动态上下线,任意一台客户端都能实时感知到主节点服务器的上下线
3、需求分析
4、先在集群上创建/servers节点
[zk: localhost:2181(CONNECTED) 10] create /servers "servers"
5、服务器端代码
import java.io.IOException;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;
public class ZKServer {
private String connectString = "node1:2181,node2:2181,node3:2181";
private int sessionTimeout = 2000;
private String parentNode = "/servers";
ZooKeeper zkClient;
// 建立连接
public void getConnection() throws IOException {
zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent event) { }
});
}
// 业务
public void business() throws InterruptedException{
System.out.println("添加节点了…");
Thread.sleep(Long.MAX_VALUE);
}
// 注册
public void regist(String hostname) throws KeeperException, InterruptedException {
String create = zkClient.create(parentNode + "/server",
hostname.getBytes(),
Ids.OPEN_ACL_UNSAFE,
CreateMode.EPHEMERAL_SEQUENTIAL);
System.out.println(hostname + " is online " + create);
}
public static void main(String[] args) throws Exception {
ZKServer zkServer = new ZKServer();
// 1 建立连接
zkServer.getConnection();
// 2 注册
zkServer.regist(args[0]);
// 3 具体业务处理
zkServer.business();
}
}
6、客户端代码
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
public class ZKClient {
private String connectString = "node1:2181,node2:2181,node3:2181";
private int sessionTimeout = 2000;
ZooKeeper zkClient;
private String parentNode = "/servers";
// 获取连接
public void getConnect() throws IOException {
zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent event) {
try {
getServersList();
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
// 监听节点变化
public void getServersList() throws KeeperException, InterruptedException{
List<String> children = zkClient.getChildren(parentNode, true);
ArrayList<String> servers = new ArrayList<>();
for (String node : children) {
byte[] data = zkClient.getData(parentNode+"/"+node, false, null);
servers.add(new String(data));
}
System.out.println(servers);
}
// 业务
public void business() throws InterruptedException{
System.out.println("节点状态");
Thread.sleep(Long.MAX_VALUE);
}
public static void main(String[] args) throws Exception {
ZKClient zk = new ZKClient();
// 1 获取连接
zk.getConnect();
// 2 监听节点变化
zk.getServersList();
// 3 业务逻辑处理
zk.business();
}
}