Skip to content

Instantly share code, notes, and snippets.

@JoshuaChi
Created April 9, 2017 08:17
Show Gist options
  • Save JoshuaChi/2745829197089d753fd6eecf69ed8502 to your computer and use it in GitHub Desktop.
Save JoshuaChi/2745829197089d753fd6eecf69ed8502 to your computer and use it in GitHub Desktop.
Zookeeper::RoundRobinBalancer
public class RoundRobinBalancer implements Balancer {
private CuratorFramework zkClient;
public RoundRobinBalancer(CuratorFramework zkClient){
this.zkClient = zkClient;
}
@Override
public String select() throws Exception {
List<String> workers = zkClient.getChildren().forPath("/workers");
if(workers == null){
return null;
}
int size = workers.size();
if(size == 0){
return null;
}
int round = -1;
SharedCount sc = new SharedCount(zkClient, "/round", -1);
boolean success = false;
try {
sc.start();
while(!success){
round = sc.getCount();
round++;
if(round >= Integer.MAX_VALUE){
round = -1;
}
success = sc.trySetCount(round);
}
}finally{
CloseableUtils.closeQuietly(sc);
}
int index = round % size;
return workers.get(index);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment