欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Curator框架简单介绍和使用

程序员文章站 2022-07-13 14:35:09
...
Curator框架简单介绍和使用


什么是Curator?
  Curator发音“kyoor͝ˌātər:”,是ZooKeeper的keeper。
“Guava is to Java what Curator is to ZooKeeper”
                                 ---Patrick Hunt, ZooKeeper commiter
使用Curator
  • 获取一个连接
  • 如果你仅需要一个ZooKeeper连接管理和重试策略的包装,使用curator-framework的包就行。Curator 连接实例(CuratorFramework)可从CuratorFrameworkFactory得到。一个
    CuratorFramework对应ZooKeeper集群,代码看起来像这样:
    RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3)
    CuratorFramework client = CuratorFrameworkFactory.newClient(zookeeperConnectionString, retryPolicy);
    client.start();

    client必须启动,当不再使用时关闭
  • 直接调用ZooKeeper
  • 一旦有了 CuratorFramework实例,你可以直接调用ZooKeeper
    client.create().forPath("/my/path", myData)

    这样一来Curator就会管理ZooKeeper连接,并且当连接错误时会有重试操作。

    秘诀
  • 分布式锁
  • InterProcessMutex lock = new InterProcessMutex(client, lockPath);
    if ( lock.acquire(maxWait, waitUnit) ) 
    {
        try 
        {
            // do some work inside of the critical section here
        }
        finally
        {
            lock.release();
        }
    }

  • 领导选举
  • LeaderSelectorListener listener = new LeaderSelectorListenerAdapter()
    {
        public void takeLeadership(CuratorFramework client) throws Exception
        {
            // this callback will get called when you are the leader
            // do whatever leader work you need to and only exit
            // this method when you want to relinquish leadership
        }
    }
    
    LeaderSelector selector = new LeaderSelector(client, path, listener);
    selector.autoRequeue();  // not required, but this is behavior that you will probably expect
    selector.start();


    公共类ZKPaths
    静态的方法,操作ZooKeeper ZNode paths
  • getNodeFromPath : 给一个全路径,返回节点名称。例子  "/one/two/three" 返回 three
  • mkdirs:创建path里的所有节点。
  • getSortedChildren:返回有序seq的子集
  • makePath:合并path和node。

  • 代码例子:
    https://github.com/apache/curator/tree/master/curator-examples


    参考
    https://cwiki.apache.org/confluence/display/CURATOR/Tech+Notes

    http://curator.apache.org/index.html