-
需求
服务提供方向zookeeper集群注册自己
服务消费方向zookeeper集群获取服务列表
当服务提供方节点下线时,服务消费方收到通知
-
创建服务节点
先使用zookeeper自带的客户端在/下创建一个永久型的servers节点
create /servers servers
-
服务提供方代码
public class DistributeServer { //连接的zookeeper集群 private String connectString = "192.168.150.129:2181,192.168.150.130:2181,192.168.150.131:2181"; //超时时间 private int sessionTimeout = 50000; private ZooKeeper zooKeeper; public static void main(String[] args) throws Exception { DistributeServer server = new DistributeServer(); // 1.连接zookeeper集群 server.init(); // 2.注册服务 server.regist(args[0]); // 3.业务逻辑 server.business(); } /** * 初始化连接 zookeeper 集群 * @throws IOException */ private void init() throws IOException { zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() { public void process(WatchedEvent watchedEvent) { } }); } /** * 注册服务 创建临时的带序号的节点 * @param host * @throws KeeperException * @throws InterruptedException */ private void regist(String host) throws KeeperException, InterruptedException { String path = zooKeeper.create("/servers/server", host.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); System.out.println(host + "服务注册成功!!"); } /** * 业务逻辑 这个的目的是让程序一直运行不退出 * @throws InterruptedException */ private void business() throws InterruptedException { TimeUnit.SECONDS.sleep(Long.MAX_VALUE); } }
-
服务消费方代码
public class DistributeClient { //连接的zookeeper集群 private String connectString = "192.168.150.129:2181,192.168.150.130:2181,192.168.150.131:2181"; //超时时间 private int sessionTimeout = 50000; private ZooKeeper zooKeeper; public static void main(String[] args) throws Exception { DistributeClient client = new DistributeClient(); // 1.连接zookeeper集群 client.init(); // 2.获取服务列表并监听 client.getChlidrenAndWatch(); // 3.业务1代码 client.business(); } /** * 初始化连接 zookeeper 集群 * @throws IOException */ private void init() throws IOException { zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() { public void process(WatchedEvent watchedEvent) { //这里面写监听处理逻辑 try { getChlidrenAndWatch(); } catch (KeeperException | InterruptedException e) { e.printStackTrace(); } } }); } /** * 获取子节点信息并监听变化 * @throws KeeperException * @throws InterruptedException */ private void getChlidrenAndWatch() throws KeeperException, InterruptedException { List<String> children = zooKeeper.getChildren("/servers", true); //保存当前存活的服务端列表 ArrayList<String> liveHosts = new ArrayList<>(); for (String child : children) { byte[] data = zooKeeper.getData("/servers/" + child, false, null); liveHosts.add(new String(data)); } System.out.println(liveHosts); } /** * 业务代码 * @throws InterruptedException */ private void business() throws InterruptedException { TimeUnit.SECONDS.sleep(Long.MAX_VALUE); } }
-
关于 IntelliJ IDEA 多开的问题
九、服务注册动态上 下线案例分析
最新推荐文章于 2024-07-16 00:52:42 发布