
com.bluejeans.utils.zookeeper.ServiceLocator Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of zookeeper-utils Show documentation
Show all versions of zookeeper-utils Show documentation
Bluejeans Zookeeper utilities
The newest version!
package com.bluejeans.utils.zookeeper;
import java.io.IOException;
import java.util.List;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
public class ServiceLocator implements PathChildrenCacheListener {
private final PathChildrenCache pathChildrenCache;
private final MODE mode;
private int rrIndex = 0;
public ServiceLocator(CuratorFramework zkClient, String path) {
this(zkClient, path, MODE.ROUND_ROBIN);
}
public ServiceLocator(CuratorFramework zkClient, String path, MODE mode) {
this.mode = mode;
this.pathChildrenCache = ZookeeperUtils.getPathChildrenCache(zkClient, path, true);
}
@Override
public void childEvent(CuratorFramework client, PathChildrenCacheEvent evt)
throws Exception {
System.out.println("childEvent in zkLoadBalancer");
}
public String getHost() {
String path = null;
ChildData response = getChild();
if(response!=null){
path = response.getPath();
path = path.substring(path.lastIndexOf('/')+1);
}
return path;
}
private ChildData getChild(){
switch(mode){
case RANDOM:
case LEAST_LOADED:
case ROUND_ROBIN:
default: return roundRobinChild();
}
}
private synchronized ChildData roundRobinChild() {
List children = pathChildrenCache.getCurrentData();
if(children.isEmpty())
return null;
if(rrIndex>=children.size())
rrIndex=0;
ChildData data = children.get(rrIndex++);
return data;
}
public enum MODE {
ROUND_ROBIN,
RANDOM,
LEAST_LOADED
}
public void close() {
try {
pathChildrenCache.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy