Curator api的使用

zookeeper在java上的客戶端用起來很是繁瑣,並且watcher只能觸發一次。因此有了ZkClient和Curator。Curator特色就是可使用Fluent風格來寫代碼。java

今天把Curator的api簡單的用了一下。apache

1.curator對節點的操做  須要curator-framework Jar包api

<dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-framework</artifactId>
            <version>2.8.0</version>
 </dependency>
 (String[] args) {
        String servers = RetryPolicy retryPolicy = ExponentialBackoffRetry()CuratorFramework curator = CuratorFrameworkFactory.()
                .connectString(servers)
                .retryPolicy(retryPolicy)
                .sessionTimeoutMs()
                        .build()curator.start(){
            curator.create().creatingParentsIfNeeded().inBackground(BackgroundCallback() {
                (CuratorFramework curatorFrameworkCuratorEvent curatorEvent) Exception {
                    System..println(curatorEvent)System..println(curatorFramework)}
            }).forPath(.getBytes())} (Exception e) {
            e.printStackTrace()}
    }

    MyCallback BackgroundCallback {

        (CuratorFramework curatorFrameworkCuratorEvent curatorEvent) Exception {
            System..println(curatorEvent)System..println(curatorFramework)}
    }


2.對節點以及子節點的監聽 須要curator-recipes  jar報session

org.apache.curatorcurator-recipes2.8.0
(String[] args) {
        String servers = RetryPolicy retryPolicy = ExponentialBackoffRetry()CuratorFramework curator = CuratorFrameworkFactory.(serversretryPolicy)curator.start(){
            PathChildrenCache childCache = PathChildrenCache(curator)childCache.start()childCache.getListenable().addListener(PathChildrenCacheListener() {
                (CuratorFramework curatorFrameworkPathChildrenCacheEvent pathChildrenCacheEvent) Exception {
                    System..println()System..println(pathChildrenCacheEvent.toString())}
            })TimeUnit..sleep()} (Exception e) {
            e.printStackTrace()}
    }
相關文章
相關標籤/搜索