package cn.smart.bigdata.zkdist;
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 DistributeClient {
private static final String connectString = "192.168.25.121:2181,192.168.25.122:2181,192.168.25.124:2181";
private static final int sessionTimeout = 30000;
private ZooKeeper zk = null;
private static final String parentNode = "/servers";
private volatile List<String> serverList;
public void getConnect() throws Exception {
zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent event) {
// 收到事件通知后的回调函数(应该是我们自己的事件处理逻辑)
try {
//重新更新服务器列表,并且注册了监听
getServerList();
} catch (Exception e) {
}
}
});
}
public void getServerList() throws Exception, Exception{
//获取服务器子节点信息,并且对父节点进行监听
List<String> children = zk.getChildren(parentNode, true);
ArrayList<String> servers = new ArrayList<String>();
for(String child:children){
byte[] data = zk.getData(parentNode + "/" + child, false, null);
servers.add(new String(data));
}
serverList = servers;
//打印服务器列表
System.out.println(serverList.toString());
}
/**
* 业务功能
* @param hostname
* @throws Exception
*/
public void handleBusiness() throws Exception{
System.out.println("client start working...");
Thread.sleep(Long.MAX_VALUE);
}
public static void main(String[] args) throws Exception {
//获取zk连接
DistributeClient client = new DistributeClient();
client.getConnect();
//获取servers的子节点信息(并监听),从中获取服务器列表
client.getServerList();
//业务功能启动
client.handleBusiness();
}
}
JavaAPI实现zookeeper连接客户端
最新推荐文章于 2024-10-28 15:08:01 发布