Zookeeper:四、实际生产环境模拟
前言
对Zookeeper实际生产环境使用情景的模拟练习。
@
一、服务器动态上下线模拟
当一个系统中存在多台服务器时,每当有服务器上下线需要动态地告知客户端进行连接调整。可以采用Zookeeper的监听机制来实现服务器动态上下线情景模拟,此时服务器集群和客户端集群对于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 测试结果