版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29963323/article/details/79045800
package com.an.zookeeper.testzookeeper;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import lombok.Getter;
import lombok.Setter;
/**
* 测试zookeeper的负载均衡轮询算法
*
* 在zookeeper的服务端有bank节点.他的子节点有五个 分别为 sub1 sub2 sub3 sub4 sub5
*
* 效果:模仿一个银行,有五个窗口,来了15个人来办理业务.15个人轮询去访问五个窗口.
* 当一个窗口宕机时,他会自动去访问下一个窗口。没有任何变化
* @author Administrator
*
*/
public class TestLoaderBalance {
private static String COONECT_STRING = "192.168.188.129:2181";
private static int SESSION_TIMEOUT = 20*1000;
//zookeeper的节点
private static String PATH = "/bank";
//存放/bank节点下的子节点的个数
private static List<String> serviceNodeLists = new ArrayList<>();
private static @Getter@Setter ZooKeeper zk;
//当前是那个位置
private static int currentIndex = 0;
private static String SUB_PREFIX = "sub";
private static int totalNum = 5;
private ZooKeeper start() throws Exception {
return new ZooKeeper(COONECT_STRING, SESSION_TIMEOUT, new Watcher() {
@Override
public void process(WatchedEvent arg0) {
try {
serviceNodeLists = zk.getChildren(PATH, true);
} catch (KeeperException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public static String doRequest() throws Exception{
currentIndex = currentIndex + 1;
for(int i=currentIndex;i<=totalNum;i++) {
if(serviceNodeLists.contains(SUB_PREFIX+currentIndex)) {
byte[] data = zk.getData(PATH+"/"+SUB_PREFIX+currentIndex, false, new Stat());
return new String(data);
}else {
currentIndex = currentIndex + 1;
}
}
for(int i=1;i<=totalNum;i++) {
if(serviceNodeLists.contains(SUB_PREFIX+i)) {
currentIndex = i;
byte[] data = zk.getData(PATH+"/"+SUB_PREFIX+currentIndex, false, new Stat());
return new String(data);
}else {
currentIndex = currentIndex + 1;
}
}
return "no this node";
}
public static void main(String[] args) throws Exception {
TestLoaderBalance test = new TestLoaderBalance();
test.setZk(test.start());
Thread.sleep(3000);
String result = null;
for(int i=1;i<=15;i++) {
Thread.sleep(1000);
result = doRequest();
System.out.println("CustomerId"+i+"\t CurrentWindow:"+test.currentIndex+"\t result:"+result);
}
}
}
当zookeeper中有一个节点时,