服务注册
public class ServiceRegister {
private static final String BASE_SERVICES = "/services";
private static final String SERVICE_NAME = "/products";
public static void register(String address, int port) {
try {
ZooKeeper zooKeeper = new ZooKeeper("localhost:2181",5000,(watchedEvent)->{});
Stat exists = zooKeeper.exists(BASE_SERVICES + SERVICE_NAME, false);
if(exists==null) {
zooKeeper.create(BASE_SERVICES + SERVICE_NAME,"".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
String server_path = address+":"+port;
// 临时节点,断网自动删除
zooKeeper.create(BASE_SERVICES + SERVICE_NAME+"/child",server_path.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL_SEQUENTIAL);
} catch (Exception e) {
e.printStackTrace();
}
}
}
服务发现
public class InitListener implements ServletContextListener {
private static final String BASE_SERVICES = "/services";
private static final String SERVICE_NAME="/products";
private ZooKeeper zooKeeper;
@Override
public void contextInitialized(ServletContextEvent sce) {
try {
zooKeeper = new ZooKeeper("localhost:2181",5000,(watchedEvent)->{
if(watchedEvent.getType() == Watcher.Event.EventType.NodeChildrenChanged && watchedEvent.getPath().equals(BASE_SERVICES+SERVICE_NAME)) {
updateServiceList();
}
});
updateServiceList();
} catch (Exception e) {
e.printStackTrace();
}
}
private void updateServiceList() {
try{
List<String> children = zooKeeper.getChildren(BASE_SERVICES + SERVICE_NAME, true);
List<String> newServerList = new ArrayList<String>();
for(String subNode:children) {
byte[] data = zooKeeper.getData(BASE_SERVICES + SERVICE_NAME + "/" + subNode, false, null);
String host = new String(data, "utf-8");
System.out.println("host:"+host);
newServerList.add(host);
}
// 负载均衡
LoadBalance.SERVICE_LIST = newServerList;
}catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void contextDestroyed(ServletContextEvent sce) {}
}