首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Apache Curator分布式锁

Apache Curator分布式锁
EN

Stack Overflow用户
提问于 2014-03-21 05:29:40
回答 2查看 4.5K关注 0票数 3

我知道Apache Curator可以做分布式锁功能,它是建立在zookeeper之上的。根据Apache策展人官方网站上发布的文档,它看起来非常容易使用。例如:

代码语言:javascript
复制
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
CuratorFramework client = CuratorFrameworkFactory.newClient("host:ip",retryPolicy);
client.start();

InterProcessSemaphoreMutex lock = new InterProcessSemaphoreMutex(client, path);
if(lock.acquire(10, TimeUnit.SECONDS))
{
     try { /*do something*/ }
     finally { lock.release(); }
}

但是"InterProcessSemaphoreMutex“的第二个参数"path”是什么意思呢?基于API它的意思是“锁的路径”,但它到底是什么呢?谁能给我举个例子?

如果我有数百万个锁,我必须创建数百万个“锁的路径”吗?zookeeper集群的最大锁数量(Znode)是否有限制?或者,当一个进程释放它时,我们可以移除这个锁吗?

EN

回答 2

Stack Overflow用户

发布于 2014-03-21 07:55:10

ZooKeeper呈现了一个看起来像分布式文件系统的东西。对于任何ZooKeeper操作、配方等,您可以将“znode”写入特定的路径并观察更改。请看这里:http://zookeeper.apache.org/doc/trunk/zookeeperOver.html#Simple+API (关于znode)。

对于策展食谱,它需要知道您想要用来执行食谱的基本路径。对于InterProcessSemaphoreMutex,路径是每个参与者都应该使用的路径。即进程1和进程2都想要争用锁。因此,它们都使用相同的路径分配锁实例,比如“/my/ InterProcessSemaphoreMutex”。将路径视为锁标识符。在同一个ZooKeeper集群中,您可以通过使用不同的路径拥有多个锁。

希望这能有所帮助(免责声明:我是策展人的主要作者)。

票数 10
EN

Stack Overflow用户

发布于 2017-06-14 15:51:00

关于收割者的一些例子。

代码语言:javascript
复制
@Test
public void     testSomeNodes() throws Exception
{

  Timing                  timing = new Timing();
  ChildReaper             reaper = null;
  CuratorFramework        client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1));
  try
  {
    client.start();

    Random              r = new Random();
    int                 nonEmptyNodes = 0;
    for ( int i = 0; i < 10; ++i )
    {
      client.create().creatingParentsIfNeeded().forPath("/test/" + Integer.toString(i));
      if ( r.nextBoolean() )
      {
        client.create().forPath("/test/" + Integer.toString(i) + "/foo");
        ++nonEmptyNodes;
      }
    }

    reaper = new ChildReaper(client, "/test", Reaper.Mode.REAP_UNTIL_DELETE, 1);
    reaper.start();

    timing.forWaiting().sleepABit();

    Stat    stat = client.checkExists().forPath("/test");
    Assert.assertEquals(stat.getNumChildren(), nonEmptyNodes);
  }
  finally
  {
    CloseableUtils.closeQuietly(reaper);
    CloseableUtils.closeQuietly(client);
  }
}

Java Code Examples for org.apache.curator.framework.recipes.locks.Reaper

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22545507

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档