業務場景:有一個集羣式的服務器,提供對外的服務,
問題一:
服務器會根據服務的負載會增加服務器,有時候增加兩臺有時候會增加多臺的服務器
,或者是有時候服務器會宕機掉線,則產生一個問題就是,服務器的集羣會產生動態的變化
。則會產生一個問題,服務器是爲客戶端提供服務的,並且客戶端有很多,則客戶端他怎麼能知道 服務器宕機或者增加 怎麼會知道
目的是,客戶端要知道哪些服務器上線哪些服務器下線,當我請求的時候才知道那些服務器可以用
需求:客戶端能夠實時的洞察到服務器的上下線的變化
解決:客戶端如何正常的訪問到,正在生存的服務器
:代碼
package cn.itcast.bigdata.zkdist;
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.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
public class DistributedServer {
private ZooKeeper zk = null;
private static final String connectString ="master:2181,slave1:2181,slave2:2181";
private static final int sessionTimeout = 2000;
private static final String parentNode = "/servers";
/**
* 創建客戶端鏈接
* @throws Exception
*/
public void getConnect() throws Exception{
zk = new ZooKeeper(connectString,sessionTimeout,new Watcher(){
@Override
public void process(WatchedEvent event){
//收到事件通知後的回調函數(應該是我自己的事件處理邏輯)
System.out.println(event.getType()+"---" + event.getPath());
try {
zk.getChildren("/",true);
} catch (KeeperException e) {
System.out.println("創建鏈接");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
/**
* 向ZK集羣註冊服務信息
* @param hostname
* @throws Exception
*/
public void registerServer(String hostname) throws Exception{
String create = zk.create(parentNode+"/server", hostname.getBytes(),Ids.CREATOR_ALL_ACL,CreateMode.EPHEMERAL_SEQUENTIAL);
System.out.println(hostname +"is online.." + create);
}
/**
* 業務功能
* @throws Exception
*/
public void handleBussiness(String hostname) throws Exception{
System.out.println(hostname + "start working");
Thread.sleep(Long.MAX_VALUE);
}
public static void main(String[] args) throws Exception {
//獲取zk鏈接
DistributedServer server =new DistributedServer();
server.getConnect();
//利用zk鏈接註冊服務器信息
server.registerServer(args[0]);
//啓動業務功能
server.handleBussiness(args[0]);
}
}