當前位置: 首頁>>代碼示例>>Java>>正文


Java ZooKeeper類代碼示例

本文整理匯總了Java中org.apache.zookeeper.ZooKeeper的典型用法代碼示例。如果您正苦於以下問題:Java ZooKeeper類的具體用法?Java ZooKeeper怎麽用?Java ZooKeeper使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


ZooKeeper類屬於org.apache.zookeeper包,在下文中一共展示了ZooKeeper類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: testInvalidSaslIds

import org.apache.zookeeper.ZooKeeper; //導入依賴的package包/類
@Test
public void testInvalidSaslIds() throws Exception {
    ZooKeeper zk = createClient();

    List<String> invalidIds = new ArrayList<String>();
    invalidIds.add("[email protected]/server.com");
    invalidIds.add("[email protected]@KERB.REALM2");

    int i = 0;
    for(String invalidId: invalidIds) {
        List<ACL> aclList = new ArrayList<ACL>();
        try {
            ACL acl = new ACL(0,new Id("sasl",invalidId));
            aclList.add(acl);
            zk.create("/invalid"+i,null,aclList,CreateMode.PERSISTENT);
            Assert.fail("SASLAuthenticationProvider.isValid() failed to catch invalid Id.");
        }
        catch (KeeperException.InvalidACLException e) {
            // ok.
        }
        finally {
            i++;
        }
    }
}
 
開發者ID:l294265421,項目名稱:ZooKeeper,代碼行數:26,代碼來源:SaslAuthTest.java

示例2: getConnectedZkClient

import org.apache.zookeeper.ZooKeeper; //導入依賴的package包/類
private ZooKeeper getConnectedZkClient() throws IOException {
    ZooKeeper zk = new ZooKeeper(HOSTPORT, CONNECTION_TIMEOUT, this);

    long start = System.currentTimeMillis();
    while (!connected) {
        long end = System.currentTimeMillis();
        if (end - start > 5000) {
            Assert.assertTrue("Could not connect with server in 5 seconds",
                    false);
        }
        try {
            Thread.sleep(200);
        } catch (Exception e) {
            LOG.warn("Interrupted");
        }
    }
    return zk;
}
 
開發者ID:l294265421,項目名稱:ZooKeeper,代碼行數:19,代碼來源:LoadFromLogTest.java

示例3: run

import org.apache.zookeeper.ZooKeeper; //導入依賴的package包/類
public void run() {
    byte b[] = new byte[256];
    try {
        for (; current < count; current++) {
            ZooKeeper zk = parent.createClient();
            try {
                zk.create(prefix + current, b, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            } finally {
                try {
                    zk.close();
                } catch (InterruptedException e) {
                    LOG.warn("Unexpected", e);
                }
            }
        }
    } catch (Throwable t) {
        LOG.error("Client create operation Assert.failed", t);
    }
}
 
開發者ID:l294265421,項目名稱:ZooKeeper,代碼行數:20,代碼來源:ClientHammerTest.java

示例4: getNewZooKeeper

import org.apache.zookeeper.ZooKeeper; //導入依賴的package包/類
/**
 * Get a new zookeeper client instance. protected so that test class can
 * inherit and pass in a mock object for zookeeper
 * 
 * @return new zookeeper client instance
 * @throws IOException
 * @throws KeeperException zookeeper connectionloss exception
 */
protected synchronized ZooKeeper getNewZooKeeper() throws IOException,
    KeeperException {
  
  // Unfortunately, the ZooKeeper constructor connects to ZooKeeper and
  // may trigger the Connected event immediately. So, if we register the
  // watcher after constructing ZooKeeper, we may miss that event. Instead,
  // we construct the watcher first, and have it block any events it receives
  // before we can set its ZooKeeper reference.
  watcher = new WatcherWithClientRef();
  ZooKeeper zk = new ZooKeeper(zkHostPort, zkSessionTimeout, watcher);
  watcher.setZooKeeperRef(zk);

  // Wait for the asynchronous success/failure. This may throw an exception
  // if we don't connect within the session timeout.
  watcher.waitForZKConnectionEvent(zkSessionTimeout);
  
  for (ZKAuthInfo auth : zkAuthInfo) {
    zk.addAuthInfo(auth.getScheme(), auth.getAuth());
  }
  return zk;
}
 
開發者ID:nucypher,項目名稱:hadoop-oss,代碼行數:30,代碼來源:ActiveStandbyElector.java

示例5: testSuperIsSuper

import org.apache.zookeeper.ZooKeeper; //導入依賴的package包/類
@Test
public void testSuperIsSuper() throws Exception {
    ZooKeeper zk = createClient();
    try {
        zk.create("/digest_read", null, Arrays.asList(new ACL(Perms.READ, otherDigestUser)), CreateMode.PERSISTENT);
        zk.create("/digest_read/sub", null, Arrays.asList(new ACL(Perms.READ, otherDigestUser)), CreateMode.PERSISTENT);
        zk.create("/sasl_read", null, Arrays.asList(new ACL(Perms.READ, otherSaslUser)), CreateMode.PERSISTENT);
        zk.create("/sasl_read/sub", null, Arrays.asList(new ACL(Perms.READ, otherSaslUser)), CreateMode.PERSISTENT);
        zk.delete("/digest_read/sub", -1);
        zk.delete("/digest_read", -1);
        zk.delete("/sasl_read/sub", -1);
        zk.delete("/sasl_read", -1);
        //If the test failes it will most likely fail with a NoAuth exception before it ever gets to this assertion
        Assert.assertEquals(authFailed.get(), 0);
    } finally {
        zk.close();
    }
}
 
開發者ID:didichuxing2,項目名稱:https-github.com-apache-zookeeper,代碼行數:19,代碼來源:SaslSuperUserTest.java

示例6: init

import org.apache.zookeeper.ZooKeeper; //導入依賴的package包/類
/**
 * 建立zk連接,並初始化root和config節點
 */
private void init() {
	loadLocalProperties();
	try {
		this.zooKeeper = new ZooKeeper(address, 1000000, new DefaultDataWatcher());
		Stat stat = this.zooKeeper.exists(PathVarConst.ROOT_PATH, null);
		if (stat == null) {
			this.zooKeeper.create(PathVarConst.ROOT_PATH, "root".getBytes(), Ids.OPEN_ACL_UNSAFE,
					CreateMode.PERSISTENT);
			this.zooKeeper.create(PathVarConst.ROOTCONF_PATH, "config".getBytes(), Ids.OPEN_ACL_UNSAFE,
					CreateMode.PERSISTENT);
		}
	} catch (Exception e) {
		LOGGER.error("zookeeper連接配置出錯,請檢查配置文件", e);
	}
}
 
開發者ID:jtjsir,項目名稱:zookeeper-test-demo,代碼行數:19,代碼來源:Client.java

示例7: verifyUnexpectedBeans

import org.apache.zookeeper.ZooKeeper; //導入依賴的package包/類
private void verifyUnexpectedBeans(Set<ObjectName> children) {
    if (allClients != null) {
        for (ZooKeeper zkc : allClients) {
            Iterator<ObjectName> childItr = children.iterator();
            while (childItr.hasNext()) {
                ObjectName clientBean = childItr.next();
                if (clientBean.toString().contains(
                        getHexSessionId(zkc.getSessionId()))) {
                    LOG.info("found name:" + zkc.getSessionId()
                            + " client bean:" + clientBean.toString());
                    childItr.remove();
                }
            }
        }
    }
    for (ObjectName bean : children) {
        LOG.info("unexpected:" + bean.toString());
    }
    TestCase.assertEquals("Unexpected bean exists!", 0, children.size());
}
 
開發者ID:l294265421,項目名稱:ZooKeeper,代碼行數:21,代碼來源:ClientBase.java

示例8: runHammer

import org.apache.zookeeper.ZooKeeper; //導入依賴的package包/類
public void runHammer(final int threadCount, final int childCount)
    throws Throwable
{
    try {
        HammerThread[] threads = new HammerThread[threadCount];
        long start = System.currentTimeMillis();
        for (int i = 0; i < threads.length; i++) {
            ZooKeeper zk = createClient();
            String prefix = "/test-" + i;
            zk.create(prefix, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            prefix += "/";
            HammerThread thread =
                new BasicHammerThread("BasicHammerThread-" + i, zk, prefix,
                        childCount);
            thread.start();

            threads[i] = thread;
        }

        verifyHammer(start, threads, childCount);
    } catch (Throwable t) {
        LOG.error("test Assert.failed", t);
        throw t;
    }
}
 
開發者ID:l294265421,項目名稱:ZooKeeper,代碼行數:26,代碼來源:ClientHammerTest.java

示例9: process

import org.apache.zookeeper.ZooKeeper; //導入依賴的package包/類
@Override
public void process(WatchedEvent event) {
	ZooKeeper zkClient = zookeeperConnManager.getZkClient();
	try {
		/* 重新注冊節點 */
		List<String> childrens = zkClient.getChildren(nodePath, this);
		EventType eventType = event.getType();
		switch (eventType) {
		case NodeChildrenChanged:
			log.info("當前注冊中心內的成功注冊的agent數量-->"
					+ childrens.stream().filter(children -> children.startsWith("agent")).count());
			break;
		default:
			break;
		}
	} catch (Exception e) {
		log.error("error", e);
	}
}
 
開發者ID:yunjiweidian,項目名稱:TITAN,代碼行數:20,代碼來源:WatchAgents.java

示例10: waitForAll

import org.apache.zookeeper.ZooKeeper; //導入依賴的package包/類
private void waitForAll(ZooKeeper[] zks, States state) throws InterruptedException {
	int iterations = 10;
	boolean someoneNotConnected = true;
       while(someoneNotConnected) {
       	if (iterations-- == 0) {
       		ClientBase.logAllStackTraces();
		throw new RuntimeException("Waiting too long");
       	}
       	
       	someoneNotConnected = false;
       	for(ZooKeeper zk: zks) {
       		if (zk.getState() != state) {
       			someoneNotConnected = true;
       		}
       	}
       	Thread.sleep(1000);
       }
}
 
開發者ID:l294265421,項目名稱:ZooKeeper,代碼行數:19,代碼來源:QuorumPeerMainTest.java

示例11: testClientRetry

import org.apache.zookeeper.ZooKeeper; //導入依賴的package包/類
@Test
public void testClientRetry() throws IOException, InterruptedException, TimeoutException{
    CountdownWatcher cdw1 = new CountdownWatcher();
    CountdownWatcher cdw2 = new CountdownWatcher();
    ZooKeeper zk = new ZooKeeper(hostPort, 10000, cdw1);
    try {
        cdw1.waitForConnected(CONNECTION_TIMEOUT);
        ZooKeeper zk2 = new ZooKeeper(hostPort, 10000, cdw2);
        try {
            States s1 = zk.getState();
            States s2 = zk2.getState();
            Assert.assertSame(s1,States.CONNECTED);
            Assert.assertSame(s2,States.CONNECTING);
            cdw1.reset();
            cdw1.waitForDisconnected(CONNECTION_TIMEOUT);
            cdw2.waitForConnected(CONNECTION_TIMEOUT);
            Assert.assertSame(zk2.getState(),States.CONNECTED);
        } finally {
            zk2.close();
        }
    } finally {
        zk.close();
    }
}
 
開發者ID:l294265421,項目名稱:ZooKeeper,代碼行數:25,代碼來源:ClientRetry.java

示例12: testRemove1

import org.apache.zookeeper.ZooKeeper; //導入依賴的package包/類
@Test
public void testRemove1() throws Exception{
    String dir = "/testRemove1";
    String testString = "Hello World";
    final int num_clients = 1;
    ZooKeeper clients[] = new ZooKeeper[num_clients];
    DistributedQueue queueHandles[] = new DistributedQueue[num_clients];
    for(int i=0; i < clients.length; i++){
        clients[i] = createClient();
        queueHandles[i] = new DistributedQueue(clients[i], dir, null);
    }

    try{
        queueHandles[0].remove();
    }catch(NoSuchElementException e){
        return;
    }
    Assert.assertTrue(false);
}
 
開發者ID:l294265421,項目名稱:ZooKeeper,代碼行數:20,代碼來源:DistributedQueueTest.java

示例13: createNremoveMelementTest

import org.apache.zookeeper.ZooKeeper; //導入依賴的package包/類
public void createNremoveMelementTest(String dir,int n,int m) throws Exception{
    String testString = "Hello World";
    final int num_clients = 2;
    ZooKeeper clients[] = new ZooKeeper[num_clients];
    DistributedQueue queueHandles[] = new DistributedQueue[num_clients];
    for(int i=0; i < clients.length; i++){
        clients[i] = createClient();
        queueHandles[i] = new DistributedQueue(clients[i], dir, null);
    }

    for(int i=0; i< n; i++){
        String offerString = testString + i;
        queueHandles[0].offer(offerString.getBytes());
    }

    byte data[] = null;
    for(int i=0; i<m; i++){
        data=queueHandles[1].remove();
    }
    Assert.assertEquals(new String(queueHandles[1].element()), testString+m);
}
 
開發者ID:didichuxing2,項目名稱:https-github.com-apache-zookeeper,代碼行數:22,代碼來源:DistributedQueueTest.java

示例14: findPrefixInChildren

import org.apache.zookeeper.ZooKeeper; //導入依賴的package包/類
/** find if we have been created earler if not create our node
 * 
 * @param prefix the prefix node
 * @param zookeeper teh zookeeper client
 * @param dir the dir paretn
 * @throws KeeperException
 * @throws InterruptedException
 */
private void findPrefixInChildren(String prefix, ZooKeeper zookeeper, String dir) 
    throws KeeperException, InterruptedException {
    List<String> names = zookeeper.getChildren(dir, false);
    for (String name : names) {
        if (name.startsWith(prefix)) {
            id = name;
            if (LOG.isDebugEnabled()) {
                LOG.debug("Found id created last time: " + id);
            }
            break;
        }
    }
    if (id == null) {
        id = zookeeper.create(dir + "/" + prefix, data, 
                getAcl(), EPHEMERAL_SEQUENTIAL);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Created id: " + id);
        }
    }

}
 
開發者ID:maoling,項目名稱:fuck_zookeeper,代碼行數:31,代碼來源:WriteLock.java

示例15: testNodeCreated

import org.apache.zookeeper.ZooKeeper; //導入依賴的package包/類
@Test
public void testNodeCreated() throws Exception {
    QuorumUtil qu = new QuorumUtil(1);
    qu.startAll();

    EventsWatcher watcher = new EventsWatcher();
    ZooKeeper zk1 = createClient(qu, 1, watcher);
    ZooKeeper zk2 = createClient(qu, 2);

    String path = "/test1-created";

    zk1.exists(path, watcher);
    qu.shutdown(1);
    zk2.create(path, new byte[2], ZooDefs.Ids.OPEN_ACL_UNSAFE,
            CreateMode.PERSISTENT);
    qu.start(1);
    watcher.waitForConnected(TIMEOUT * 1000L);
    watcher.assertEvent(TIMEOUT, EventType.NodeCreated);

    qu.shutdownAll();
}
 
開發者ID:maoling,項目名稱:fuck_zookeeper,代碼行數:22,代碼來源:WatchEventWhenAutoReset.java


注:本文中的org.apache.zookeeper.ZooKeeper類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。