package cn.smart.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 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";
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 (Exception e) {
}
}
});
}
public void registerServer(String hostname) throws Exception, Exception{
String create = zk.create(parentNode+"/server", hostname.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
System.out.println(hostname + "is online...." + create);
}
public void handleBusiness(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.getConnect();
//利用zk连接注册服务器信息
server.registerServer(args[0]);
//启动业务功能
server.handleBusiness(args[0]);
}
}
javaAPI实现创建zookeeper服务端
最新推荐文章于 2024-01-05 10:11:54 发布