我知道Apache Curator可以做分布式锁功能,它是建立在zookeeper之上的。根据Apache策展人官方网站上发布的文档,它看起来非常容易使用。例如:
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)是否有限制?或者,当一个进程释放它时,我们可以移除这个锁吗?
发布于 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集群中,您可以通过使用不同的路径拥有多个锁。
希望这能有所帮助(免责声明:我是策展人的主要作者)。
发布于 2017-06-14 15:51:00
关于收割者的一些例子。
@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
https://stackoverflow.com/questions/22545507
复制相似问题