前言
对Zookeeper实际生产环境使用情景的模拟练习。
文章目录
一、服务器动态上下线模拟
服务器集群需要通过
create
、delete
方法实现机器上下线;客户端集群通过
get -w
、ls -w
实现对节点的监听。
1.1 服务器集群设计
/**
* 服务器动态上下线——服务器端
*/
public class ServerTest {
// Zookeeper集群
private static ZooKeeper zk = null;
// Zookeeper集群服务器名称
private static String ZK_SERVER_ADDRESS = "192.168.1.6:2181,192.168.1.7:2181,192.168.1.8:2181";
public static void main(String[] args) throws Exception{
createConnection(ZK_SERVER_ADDRESS,60000);
registerServer(args[0]);
dobusiness();
}
/**
* 1.建立连接
*/
public static void createConnection(final String hostName, int sessionTime) throws Exception{
zk = new ZooKeeper(hostName, sessionTime, new Watcher() {
public void process(WatchedEvent watchedEvent) {
System.out.println("服务器"+hostName+"上线了.....");
}
});
}
/**
* 2.注册服务器到zk集群
* 注意创建的是临时有序节点
*/
public static void registerServer(String serverName) throws Exception{
zk.create("/servers/"+serverName,serverName.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
}
/**
* 3.服务器业务操作
*/
public static void dobusiness() throws Exception{
Thread.sleep(Integer.MAX_VALUE);
}
}
1.2 客户端集群监听设计
/**
* 服务器动态上下线——客户端
*/
public class ClientTest {
// Zookeeper集群
private static ZooKeeper zk = null;
// Zookeeper集群服务器名称
private static String ZK_SERVER_ADDRESS = "192.168.1.6:2181,192.168.1.7:2181,192.168.1.8:2181";
public static void main(String[] args) throws Exception{
createConnection(ZK_SERVER_ADDRESS,60000);
// monitorServer();
dobusiness();
}
/**
* 1.建立连接
*/
public static void createConnection(final String hostName, int sessionTime) throws Exception{
zk = new ZooKeeper(hostName, sessionTime, new Watcher() {
public void process(WatchedEvent watchedEvent) {
try {
monitorServer();
} catch (Exception e) {
e.printstacktrace();
}
}
});
}
/**
* 2.监听服务器节点
* 将上线的服务器名称信息存储到集合中等待使用
*/
public static void monitorServer() throws Exception{
List<String > list = new ArrayList<String>();
List<String> children = zk.getChildren("/servers", true);
for (String child : children) {
String nodeName = new String(zk.getData("/servers/"+child,false,null));
list.add(nodeName);
}
System.out.println("------------当前服务器集合------------");
System.out.println(list.toString());
}
/**
* 3.业务操作
*/
public static void dobusiness() throws Exception{
Thread.sleep(Integer.MAX_VALUE);
}
}
1.3 测试结果
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。