zookeeper 伺服器動態上下執行緒序小Demo
伺服器端
public class DistributedServer {
private ZooKeeper zKeeper = null;
private static final String connectString = "192.168.203.129:2181,192.168.203.130:2181,192.168.203.131:2181";
private static final int sessionTimeout = 2000;
private static final String parentNode = "/servers";
/*
* 建立到zk的客戶端連線
*/
public void getContect() throws IOException {
zKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent event) {
}
});
}
/*
* 向zk叢集註冊伺服器資訊
*/
public void registerServer(String hostname ) throws Exception{
String create= zKeeper.create(parentNode+"/server", hostname.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
System.out.println(hostname + "is online..." + create);
}
/*
* 業務功能
*/
public void handleBussiness(String hostname) throws Exception {
System.out.println(hostname + "is Working.....");
Thread.sleep(Long.MAX_VALUE);
}
public static void main(String[] args) throws Exception {
//獲取zk連線
DistributedServer server = new DistributedServer();
server.getContect();
//註冊伺服器資訊
server.registerServer(args[0]);
//業務邏輯
server.handleBussiness(args[0]);
}
}
客戶端
public class DistributedClient {
private ZooKeeper zKeeper = null;
private static final String connectString = "192.168.203.129:2181,192.168.203.130:2181,192.168.203.131:2181";
private static final int sessionTimeout = 2000;
private static final String parentNode = "/servers";
//加volatile
private volatile List<String> serversList;
/*
* 建立到zk的客戶端連線
*/
public void getContect() throws IOException {
zKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent event) {
try {
//重新更新伺服器列表,並且註冊監聽
getServerList();
} catch (Exception e) {
}
}
});
}
/*
* 獲取伺服器資訊列表
*/
public void getServerList() throws Exception {
List<String> children = zKeeper.getChildren(parentNode, true);
List<String> servers = new ArrayList<String>();
for(String child:children) {
byte[] data =zKeeper.getData(parentNode+"/"+child, false, null);
servers.add(new String(data));
}
serversList = servers;
System.out.println(serversList);
}
/*
* 業務功能
*/
public void handleBussiness() throws Exception {
System.out.println("client is Working.....");
Thread.sleep(Long.MAX_VALUE);
}
public static void main(String[] args) throws Exception{
//獲取zk連線
DistributedClient client = new DistributedClient();
client.getContect();
//獲取servers 的節點資訊(並監聽),從中獲取伺服器資訊列表
client.getServerList();
client.handleBussiness();
}
}