使用zk实现超mini注册中心


            org.apache.curator
            curator-framework
            2.4.0


            org.apache.curator
            curator-recipes
            2.4.0

使用 Server 改变url发送2次创建临时节点:

public class Server {
    public static void main(String[] args) {
        // 1 重试策略:初试时间为1s 重试10次
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 10);
        // 2 通过工厂创建连接
        CuratorFramework cf = CuratorFrameworkFactory.builder()
                .connectString("localhost:2181")
                .sessionTimeoutMs(1000 * 10)
                .retryPolicy(retryPolicy)
                .build();
        // 3 开启连接
        cf.start();
        try {
            // 4. 模拟本机ip
            cf.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath("/urls/192.168.0.11");
            Thread.sleep(200000000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

启动 Client

public class Client {
    public static void main(String[] args) {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 10);
        CuratorFramework cf = CuratorFrameworkFactory.builder()
                .connectString("localhost:2181")
                .sessionTimeoutMs(1000 * 10)
                .retryPolicy(retryPolicy)
                .build();
        cf.start();

        try {
            final PathChildrenCache childrenCache = new PathChildrenCache(cf, "/urls", true);
            childrenCache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
            childrenCache.getListenable().addListener(
                    (client, event) -> {
                        switch (event.getType()) {
                            case CHILD_ADDED:
                                System.out.println("CHILD_ADDED: " + event.getData().getPath());
                                break;
                            case CHILD_REMOVED:
                                System.out.println("CHILD_REMOVED: " + event.getData().getPath());
                                break;
                            case CHILD_UPDATED:
                                System.out.println("CHILD_UPDATED: " + event.getData().getPath());
                                break;
                            default:
                                break;
                        }
                    }
            );
            List urls = cf.getChildren().forPath("/urls");
            for (String url : urls) {
                System.out.println(url);
            }
            Thread.sleep(200000000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

运行图:


image.png

下掉一个节点之后:


image.png

你可能感兴趣的:(使用zk实现超mini注册中心)