- 模拟上游服务上下线操作
package com.ruiclear.test.zookeeper;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import java.util.List;
import java.util.Random;
/**
* @author RuiClear
* @date 2020-05-21 15:57
*/
public class Server {
public static void main(String[] args) throws Exception{
ZooKeeper zk = new ZooKeeper("localhost:2181",5000, (e) ->{
System.out.println(e.getPath()+":"+e.getType());
});
new Thread(() ->{
for(int i=0;i<40;i++) {
try {
String s = zk.create("/rui/life", ("10.2.11."+i).getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
System.out.println(s+" is online!");
Thread.sleep(2000);
}catch (Exception e){
e.printStackTrace();
}
}
}).start();
Random random = new Random();
new Thread(() ->{
try {
for(int i=0;i<100;i++) {
List<String> list = zk.getEphemerals("/");
if(list.size() > 0){
String s = list.get(random.nextInt(list.size()));
zk.delete(s,-1);
System.out.println(s+" is offline!");
}
Thread.sleep(4000);
}
}catch (Exception e){
e.printStackTrace();
}
}).start();
}
}
- 模拟下游感知上游服务上下线状态
package com.ruiclear.test.zookeeper;
import org.apache.commons.lang.StringUtils;
import org.apache.zookeeper.ZooKeeper;
import java.util.ArrayList;
import java.util.List;
/**
* @author RuiClear
* @date 2020-05-21 15:56
*/
public class Client {
static ZooKeeper zk;
public static void main(String[] args) throws Exception{
zk = new ZooKeeper("localhost:2181",5000, (e) ->{
try {
getList();
} catch (Exception ex) {
ex.printStackTrace();
}
});
getList();
Thread.sleep(Integer.MAX_VALUE);
}
public static void getList() throws Exception{
List<String> children = zk.getChildren("/rui", true);
List<String> servers = new ArrayList<>();
for (String s:children){
byte[] data = zk.getData("/rui/"+s, false, null);
servers.add(new String(data));
}
System.out.println("servers: "+StringUtils.join(servers,","));
}
}