天天看點

java zookeeper 例子,Java ZooKeeper.multi方法代碼示例

import org.apache.zookeeper.ZooKeeper; //導入方法依賴的package包/類

@Test

public void ephemeralCreateMultiOpTest() throws KeeperException, InterruptedException, IOException {

final ZooKeeper zk = createClient();

String data = "test";

String path = "/ephemeralcreatemultiop";

zk.create(path, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

QuorumZooKeeperServer server = getConnectedServer(zk.getSessionId());

Assert.assertNotNull("unable to find server interlocutor", server);

UpgradeableSessionTracker sessionTracker = (UpgradeableSessionTracker)server.getSessionTracker();

Assert.assertFalse("session already global", sessionTracker.isGlobalSession(zk.getSessionId()));

List multi = null;

try {

multi = zk.multi(Arrays.asList(

Op.setData(path, data.getBytes(), 0),

Op.create(path + "/e", data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL),

Op.create(path + "/p", data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT),

Op.create(path + "/q", data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL)

));

} catch (KeeperException.SessionExpiredException e) {

// the scenario that inspired this unit test

Assert.fail("received session expired for a session promotion in a multi-op");

}

Assert.assertNotNull(multi);

Assert.assertEquals(4, multi.size());

Assert.assertEquals(data, new String(zk.getData(path + "/e", false, null)));

Assert.assertEquals(data, new String(zk.getData(path + "/p", false, null)));

Assert.assertEquals(data, new String(zk.getData(path + "/q", false, null)));

Assert.assertTrue("session not promoted", sessionTracker.isGlobalSession(zk.getSessionId()));

}