如何使用Curator.x.discovery注册服务ZooKeeper

时间:2018-01-04 09:06:39

标签: java apache-zookeeper service-discovery apache-curator

我正在尝试在int port上注册一个简单的REST服务, 到localhost:2181的ZooKeeper服务器。 我也使用zooClient检查了路径ls /。 有任何想法吗?

private static void registerInZookeeper(int port) throws Exception {
CuratorFramework curatorFramework = CuratorFrameworkFactory
        .newClient("localhost:2181", new RetryForever(5));

curatorFramework.start();

ServiceInstance<Object> serviceInstance = ServiceInstance.builder()
        .address("localhost")
        .port(port)
        .name("worker")
        .uriSpec(new UriSpec("{scheme}://{address}:{port}"))
        .build();

ServiceDiscoveryBuilder.builder(Object.class)
        .basePath("myNode")
        .client(curatorFramework)
        .thisInstance(serviceInstance)
        .build()
        .start();

Optional.ofNullable(curatorFramework.checkExists().forPath("/zookeeper")).ifPresent(System.out::println);
Optional.ofNullable(curatorFramework.checkExists().forPath("/myNode")).ifPresent(System.out::println);
}

3 个答案:

答案 0 :(得分:0)

这里的注册码看起来是正确的。为了打印已注册的实例,可以执行以下代码:

    Optional.ofNullable(curatorFramework.getChildren().forPath("/myNode/worker"))
            .orElse(Collections.emptyList())
            .forEach(childNode -> {
                try {
                    System.out.println(childNode);
                    System.out.println(new String(curatorFramework.getData().forPath("/myNode/worker/" + childNode)));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

结果就像

07:23:12.353 INFO  [main-EventThread] ConnectionStateManager:228 - State change: CONNECTED

48202336-e89b-4724-912b-89620f7c9954
{"name":"worker","id":"48202336-e89b-4724-912b-89620f7c9954","address":"localhost","port":1000,"sslPort":null,"payload":null,"registrationTimeUTC":1515561792319,"serviceType":"DYNAMIC","uriSpec":{"parts":[{"value":"scheme","variable":true},{"value":"://","variable":false},{"value":"address","variable":true},{"value":":","variable":false},{"value":"port","variable":true}]}}

答案 1 :(得分:0)

由于compatibility issues

,我一直从Zoo Server接收Received packet at server of unknown type 15

答案 2 :(得分:0)

创建具有zk34(kafka使用的版本)兼容性的策展人框架应该可以解决您的问题

    private CuratorFramework buildFramework(String ip) {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        return CuratorFrameworkFactory.builder().zk34CompatibilityMode(true).connectString(ip + ":2181")
                .retryPolicy(retryPolicy).build();
    }

请注意,策展人将尽力而为,一些新方法(例如,creatingParentsIfNeeded(确定)与creatingParentContainersIfNeeded(确定))将会失败。