Created
April 9, 2017 08:18
-
-
Save JoshuaChi/a906467430285b4e3af10054ed02e7e4 to your computer and use it in GitHub Desktop.
Zookeeper::LeastConnectionBalancer
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 LeastConnectionBalancer implements Balancer { | |
private CuratorFramework zkClient; | |
public LeastConnectionBalancer(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 leastConnection = -1; | |
int leastNode = -1; | |
for(int i=0; i<size; i++){ | |
/** | |
* 同时,在Server程序中,当channelActive的时候,ZooKeeper记录的连接数要增加1; | |
* 当channelInactive的时候,ZooKeeper记录的连接数要减少1。 | |
*/ | |
byte[] data = zkClient.getData().forPath("/workers/" + workers.get(i)); | |
int connection = Integer.parseInt(new String(data)); | |
if(leastConnection == -1 || connection < leastConnection){ | |
leastConnection = connection; | |
leastNode = i; | |
} | |
} | |
return workers.get(leastNode); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment