十三、curator recipes之SharedCounter

简介

我们可以通过curator实现对一个分布式环境下共享变量的访问,zookeeper将共享变量维护在同一个路径下。

官方文档: http://curator.apache.org/curator-recipes/shared-counter.html

javaDoc:http://curator.apache.org/apidocs/org/apache/curator/framework/recipes/shared/SharedCount.html

代码示例

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.shared.SharedCount;
import org.apache.curator.framework.recipes.shared.SharedCountListener;
import org.apache.curator.framework.recipes.shared.SharedCountReader;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class SharedCounterDemo {
    private static CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181", new ExponentialBackoffRetry(3000, 2));
    private static String path = "/shared/counter/0001";
    private static SharedCount count = new SharedCount(client, path, 0);
    static {
        client.start();
    }

    public static void main(String[] args) throws Exception {
        count.start();
        count.addListener(new SharedCountListener() {
            @Override
            public void countHasChanged(SharedCountReader sharedCountReader, int i) throws Exception {
                System.out.println("count changed value is " + i);
            }

            @Override
            public void stateChanged(CuratorFramework curatorFramework, ConnectionState connectionState) {
                System.out.println("stateChanged isConnected: " + connectionState.isConnected());
            }
        });
        count.setCount(10);
        System.out.println("count: " + count.getCount());
        Thread.sleep(50000);
        client.close();
    }
}

 

posted @ 2019-01-16 12:41  __lay  阅读(278)  评论(0编辑  收藏  举报