3

我知道 Apache Curator 可以执行构建在 zookeeper 之上的分布式锁功能。根据 Apache Curator 官方网站上发布的文档,它看起来非常易于使用。例如:

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 集群的最大锁数(znodes)是否有限制?或者我们可以在进程释放它时移除这个锁吗?

4

2 回答 2

10

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

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

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

于 2014-03-20T23:55:10.373 回答
2

关于收割者的一些例子。

@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);
  }
}

org.apache.curator.framework.recipes.locks.Reaper 的 Java 代码示例

于 2017-06-14T07:50:59.797 回答