# 过程
- 创建持久化的根节点
/server-pig
- 客户端监听
/server-pig
节点下的子节点的上线/下线,当有节点上线,说明有新的服务可用,当有节点下线,说明有服务停止提供服务了。 - 服务端,服务提供者,当实例上线,向
/server-pig
节点下创建子节点(非持久化节点),当实例断开连接后,ZK会自动将其剔除。
# 代码
- 客户端监听
package com.futao.zookeeper.dynamic; import lombok.SneakyThrows; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; /** * 客户端监听服务实例的变化 * * @author ft * @date 2021/8/3 */ public class Client { private static ZooKeeper Zk = null; public static void main(String[] args) throws IOException, InterruptedException { Zk = new ZooKeeper("zk1.local:2181,zk2.local:2182,zk3.local:2183", 2000, new Watcher() { @SneakyThrows @Override public void process(WatchedEvent event) { // 可用的实例列表 List<String> serverList = new ArrayList<>(); List<String> children = Zk.getChildren("/server-pig", true); for (String child : children) { byte[] data = Zk.getData("/server-pig/" + child, false, null); // 拿到的是节点名,而不是data,why? serverList.add(new String(data)); } System.out.println(children); } }); // 阻塞主线程 TimeUnit.HOURS.sleep(1); } }
- 服务端,模拟三个服务端
package com.futao.zookeeper.dynamic; import com.futao.zookeeper.Zk; import org.apache.zookeeper.*; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.concurrent.TimeUnit; /** * @author ft * @date 2021/8/3 */ public class Server { private static ZooKeeper zooKeeper = null; public static void main(String[] args) throws IOException, InterruptedException, KeeperException { zooKeeper = new ZooKeeper(Zk.CONNECTION_STRING, 2000, new Watcher() { @Override public void process(WatchedEvent event) { System.out.println("事件:" + event); } }); // 节点 String serverName = "/server-pig/server-1"; // 创建的是非持久化的且带序列号的节点 zooKeeper.create(serverName, "服务器1".getBytes(StandardCharsets.UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); System.out.println(serverName + " 创建成功"); //保持在线状态 TimeUnit.HOURS.sleep(1); } }
- 服务器1:
String serverName = "/server-pig/server-1";
- 服务器2:
String serverName = "/server-pig/server-2";
- 服务器3:
String serverName = "/server-pig/server-3";
- 分别上线,查看Client状态
服务端下线:
这样就实现了服务的动态上下线。客户端监听可用服务实例列表,进行服务调用。