Created
April 9, 2017 08:17
-
-
Save JoshuaChi/2745829197089d753fd6eecf69ed8502 to your computer and use it in GitHub Desktop.
Zookeeper::RoundRobinBalancer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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