上一篇中提过zk可以用来做服务器上下线动态感知,今天就来写这个东西,当然,肯定距离生产环境下的代码质量相差深甚远,不断前行努力吧~~
1、需求简单描述
在某个分布式系统中,主节点可以有多台,可以动态上下线,任意一台客户端都能实时感知到主节点服务器的上下线。
设计思路:
对于服务器异常宕机的处理类似,省去不表。
2、代码开发
服务端程序
package zk_dist;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import java.util.concurrent.CountDownLatch;
/**
* Created by Cage on 2016/10/17.
*/
public class DistributerServer {
private static final String CONNECT_STRING = "had01:2181,had02:2181,had03:2181";
private static final int SESSION_TIMEOUT = 2000;
private static final String PARENT_NODE = "/servers";
private ZooKeeper zk = null;
private CountDownLatch countDownLatch = new CountDownLatch(1);
/**
* 创建ZK的客户端连接
*/
public void getConnect() throws Exception{
zk = new ZooKeeper(CONNECT_STRING, SESSION_TIMEOUT, new Watcher() {
public void process(WatchedEvent watchedEvent) {
if(watchedEvent.getState() == Event.KeeperState.SyncConnected){
countDownLatch.countDown();
}
}
});
countDownLatch.await();
}
/**
* 向ZK集群注册服务器消息
* @param hostname
* @throws Exception
*/
public void registerSerever(String hostname) throws Exception{
Stat exists = zk.exists(PARENT_NODE,false);
if(exists == null){
zk.create(PARENT_NODE,null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
String path = zk.create(PARENT_NODE+"/server",hostname.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL);
System.out.println(hostname+" is online..."+path);
}
/**
* 业务功能
* @param hostname
* @throws InterruptedException
*/
public void handleBussiness(String hostname)throws InterruptedException{
System.out.println(hostname + " start working....");
Thread.sleep(Long.MAX_VALUE);
}
public static void main(String[] args) throws Exception {
DistributerServer server = new DistributerServer();
//获取ZK连接
server.getConnect();
//利用ZK连接注册服务器信息(主机名)
server.registerSerever(args[0]);
//启动业功能
server.handleBussiness(args[0]);
}
}
运行三次(模拟3个服务器上线),结果如下图:
主机名有三个:cage,tom,slice,还有两个未贴出。在IDEA控制台也有输出:
接下来看客户端程序:
package zk_dist;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Cage on 2016/10/17.
*/
public class DistributeClient {
private static final String CONNECT_STRING = "had01:2181,had02:2181,had03:2181";
private static final int SESSION_TIMEOUT = 2000;
private static final String PARENT_NODE = "/servers";
private volatile List<String> serverList;
private ZooKeeper zk = null;
public void getConnect() throws Exception{
zk = new ZooKeeper(CONNECT_STRING, SESSION_TIMEOUT, new Watcher() {
public void process(WatchedEvent watchedEvent) {
//收到事件通知后的回调函数,
try{
getServerList();
}catch (Exception e){
e.printStackTrace();
}
}
});
}
/**
* 获取服务器信息列表
* @throws Exception
*/
public void getServerList() throws Exception{
//获取服务器子节点信息,并且对父节点进行监听
List<String> children = zk.getChildren(PARENT_NODE,true);
//先创建一个局部的list来保存服务器信息
List<String> servers = new ArrayList<String>();
for(String child : children){
//child只是子节点节点名
byte[] data = zk.getData(PARENT_NODE+"/"+child,false,null);
servers.add(new String(data));
}
//把servers复赋值给成员变量给serverList,已提供给各业务线程使用
serverList = servers;
//打印服务器列表
System.out.println(serverList);
}
/**
* 业务功能
* @throws InterruptedException
*/
public void handleBusiness() throws InterruptedException{
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();
}
}
运行之后,是这样的:
现在,模拟新增加一台服务器并上线,命名为Jordan:
运行服务端程序,结果:
在客户端会自动获取一个新的服务器列表:
好了。大概演示到这里。具体的应用场景还是蛮多的,自己慢慢体会吧~~