首页 >常见问题 >apache curator怎么操作zookeeper

apache curator怎么操作zookeeper

王林
王林转载
2021-01-12 10:23:491802浏览

apache curator怎么操作zookeeper

apache curator怎么操作zookeeper?

(学习视频分享:编程视频

首先来简单介绍下apache curator。

Apache Curator是Apache ZooKeeper的Java / JVM客户端库,Apache ZooKeeper是一种分布式协调服务。它包括一个高级API框架和实用程序,使Apache ZooKeeper更容易和更可靠。它还包括常见用例和扩展(如服务发现和Java 8异步DSL)的配方。

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

Curator项目组件(下载官方源码就可以看到以下组件)

1f196363edfe7aa0a3ba4123ad701e1.png

Maven依赖(地址:https://search.maven.org/search?q=org.apache.curator)

5470e0fb41e05de96cc77829e7e0908.png

分布式锁实现

<dependency>
  <groupId>org.apache.curator</groupId>
  <artifactId>curator-recipes</artifactId>
  <version>4.1.0</version>
</dependency>
public static void main(String[] args) {
        String zookeeperConnectionString = "localhost:2181";
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.newClient(zookeeperConnectionString, retryPolicy);
        client.start();
 
        try {
            //创建分布式锁, 锁空间的根节点路径为/curator/lock
            InterProcessMutex lock = new InterProcessMutex(client, "/curator/lock");
            if ( lock.acquire(1000, TimeUnit.SECONDS) )
            {
                try
                {
                    // do some work inside of the critical section here
                    System.out.println("do some work inside of the critical section here");
                }
                finally
                {
                    //完成业务流程, 释放锁
                    lock.release();
                }
            }
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

相关推荐:apache教程

以上是apache curator怎么操作zookeeper的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:csdn.net。如有侵权,请联系admin@php.cn删除