当前位置: 首页>>代码示例>>Java>>正文


Java ZooKeeper.getSessionId方法代码示例

本文整理汇总了Java中org.apache.zookeeper.ZooKeeper.getSessionId方法的典型用法代码示例。如果您正苦于以下问题:Java ZooKeeper.getSessionId方法的具体用法?Java ZooKeeper.getSessionId怎么用?Java ZooKeeper.getSessionId使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.apache.zookeeper.ZooKeeper的用法示例。


在下文中一共展示了ZooKeeper.getSessionId方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: testSessionEstablishment

import org.apache.zookeeper.ZooKeeper; //导入方法依赖的package包/类
/**
 * Tests a situation when client firstly connects to a read-only server and
 * then connects to a majority server. Transition should be transparent for
 * the user.
 */
@Test(timeout = 90000)
public void testSessionEstablishment() throws Exception {
    qu.shutdown(2);

    CountdownWatcher watcher = new CountdownWatcher();
    ZooKeeper zk = new ZooKeeper(qu.getConnString(), CONNECTION_TIMEOUT,
            watcher, true);
    watcher.waitForConnected(CONNECTION_TIMEOUT);
    Assert.assertSame("should be in r/o mode", States.CONNECTEDREADONLY, zk
            .getState());
    long fakeId = zk.getSessionId();

    watcher.reset();
    qu.start(2);
    Assert.assertTrue("waiting for server up", ClientBase.waitForServerUp(
            "127.0.0.1:" + qu.getPeer(2).clientPort, CONNECTION_TIMEOUT));
    watcher.waitForConnected(CONNECTION_TIMEOUT);
    zk.create("/test", "test".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
            CreateMode.PERSISTENT);
    Assert.assertFalse("fake session and real session have same id", zk
            .getSessionId() == fakeId);

    zk.close();
}
 
开发者ID:maoling,项目名称:fuck_zookeeper,代码行数:30,代码来源:ReadOnlyModeTest.java

示例2: testSessionEstablishment

import org.apache.zookeeper.ZooKeeper; //导入方法依赖的package包/类
/**
 * Tests a situation when client firstly connects to a read-only server and
 * then connects to a majority server. Transition should be transparent for
 * the user.
 */
@Test(timeout = 90000)
public void testSessionEstablishment() throws Exception {
    qu.shutdown(2);

    CountdownWatcher watcher = new CountdownWatcher();
    ZooKeeper zk = new ZooKeeper(qu.getConnString(), CONNECTION_TIMEOUT,
            watcher, true);
    watcher.waitForConnected(CONNECTION_TIMEOUT);
    Assert.assertSame("should be in r/o mode", States.CONNECTEDREADONLY, zk
            .getState());
    long fakeId = zk.getSessionId();
    LOG.info("Connected as r/o mode with state {} and session id {}",
            zk.getState(), fakeId);

    watcher.reset();
    qu.start(2);
    Assert.assertTrue("waiting for server up", ClientBase.waitForServerUp(
            "127.0.0.1:" + qu.getPeer(2).clientPort, CONNECTION_TIMEOUT));
    LOG.info("Server 127.0.0.1:{} is up", qu.getPeer(2).clientPort);
    // ZOOKEEPER-2722: wait until we can connect to a read-write server after the quorum
    // is formed. Otherwise, it is possible that client first connects to a read-only server,
    // then drops the connection because of shutting down of the read-only server caused
    // by leader election / quorum forming between the read-only server and the newly started
    // server. If we happen to execute the zk.create after the read-only server is shutdown and
    // before the quorum is formed, we will get a ConnectLossException.
    watcher.waitForSyncConnected(CONNECTION_TIMEOUT);
    Assert.assertEquals("Should be in read-write mode", States.CONNECTED,
            zk.getState());
    LOG.info("Connected as rw mode with state {} and session id {}",
            zk.getState(), zk.getSessionId());
    zk.create("/test", "test".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
            CreateMode.PERSISTENT);
    Assert.assertFalse("fake session and real session have same id", zk
            .getSessionId() == fakeId);
    zk.close();
}
 
开发者ID:didichuxing2,项目名称:https-github.com-apache-zookeeper,代码行数:42,代码来源:ReadOnlyModeTest.java

示例3: connect1

import org.apache.zookeeper.ZooKeeper; //导入方法依赖的package包/类
public static void connect1() {

        final CountDownLatch connectCountDown = new CountDownLatch(1);

        try {
            /**
             * 参数1: zk的连接字符串
             * 参数2: zk的连接超时时间
             * 参数3: zk连接后的监听watcher
             */
            ZooKeeper keeper = new ZooKeeper(ZK_CONNECT_STR, SESSION_TIMEOUT, new Watcher() {
                public void process(WatchedEvent event) {
                    // 连接成功时计数器减1
                    if (event.getState() == Event.KeeperState.SyncConnected) {
                        connectCountDown.countDown();
                    }
                }
            });

            // 未连接成功时一直在这里阻塞
            connectCountDown.await();

            long sessionId = keeper.getSessionId();

            System.out.println(sessionId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
开发者ID:cbooy,项目名称:cakes,代码行数:30,代码来源:CreateConnectionDemos.java

示例4: testOpenCloseSession

import org.apache.zookeeper.ZooKeeper; //导入方法依赖的package包/类
/**
 * Test that a CloseSession request generated by both the server (client
 * disconnect) or by the client (client explicitly issue close()) doesn't
 * get committed by the ensemble
 */
public void testOpenCloseSession(boolean onLeader) throws Exception {
    int leaderIdx = qb.getLeaderIndex();
    Assert.assertFalse("No leader in quorum?", leaderIdx == -1);
    int followerIdx = (leaderIdx + 1) % 5;
    int testPeerIdx = onLeader ? leaderIdx : followerIdx;
    int verifyPeerIdx = onLeader ? followerIdx : leaderIdx;

    String hostPorts[] = qb.hostPort.split(",");

    CountdownWatcher watcher = new CountdownWatcher();
    DisconnectableZooKeeper client = new DisconnectableZooKeeper(
            hostPorts[testPeerIdx], CONNECTION_TIMEOUT, watcher);
    watcher.waitForConnected(CONNECTION_TIMEOUT);

    long localSessionId1 = client.getSessionId();

    // Cut the connection, so the server will create closeSession as part
    // of expiring the session.
    client.dontReconnect();
    client.disconnect();
    watcher.reset();

    // We don't validate right away, will do another session create first

    ZooKeeper zk = qb.createClient(watcher, hostPorts[testPeerIdx],
            CONNECTION_TIMEOUT);
    watcher.waitForConnected(CONNECTION_TIMEOUT);

    long localSessionId2 = zk.getSessionId();

    // Send closeSession request.
    zk.close();
    watcher.reset();

    // This should be enough time for the first session to expire and for
    // the closeSession request to propagate to other machines (if there is a bug)
    // Since it is time sensitive, we have false negative when test
    // machine is under load
    Thread.sleep(CONNECTION_TIMEOUT * 2);

    // Validate that we don't see any txn from the first session
    validateRequestLog(localSessionId1, verifyPeerIdx);

    // Validate that we don't see any txn from the second session
    validateRequestLog(localSessionId2, verifyPeerIdx);

    qb.shutdownServers();

}
 
开发者ID:didichuxing2,项目名称:https-github.com-apache-zookeeper,代码行数:55,代码来源:LocalSessionRequestTest.java

示例5: testLocalSessions

import org.apache.zookeeper.ZooKeeper; //导入方法依赖的package包/类
private void testLocalSessions(boolean testLeader) throws Exception {
    String nodePrefix = "/testLocalSessions-"
        + (testLeader ? "leaderTest-" : "followerTest-");
    int leaderIdx = qb.getLeaderIndex();
    Assert.assertFalse("No leader in quorum?", leaderIdx == -1);
    int followerIdx = (leaderIdx + 1) % 5;
    int testPeerIdx = testLeader ? leaderIdx : followerIdx;
    String hostPorts[] = qb.hostPort.split(",");

    CountdownWatcher watcher = new CountdownWatcher();
    ZooKeeper zk = qb.createClient(watcher, hostPorts[testPeerIdx],
                                   CONNECTION_TIMEOUT);
    watcher.waitForConnected(CONNECTION_TIMEOUT);

    long localSessionId = zk.getSessionId();

    // Try creating some data.
    for (int i = 0; i < 5; i++) {
        zk.create(nodePrefix + i, new byte[0],
                  ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    // Now, try an ephemeral node.  This should fail since we
    // cannot create ephemeral nodes on a local session.
    try {
        zk.create(nodePrefix + "ephemeral", new byte[0],
                  ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        Assert.fail("Ephemeral node creation should fail.");
    } catch (KeeperException.EphemeralOnLocalSessionException e) {
    }

    // Close the session.
    zk.close();

    // Validate data on both follower and leader
    Map<String, Integer> peers = new HashMap<String, Integer>();
    peers.put("leader", leaderIdx);
    peers.put("follower", followerIdx);
    for (Entry<String, Integer> entry: peers.entrySet()) {
        watcher.reset();
        // Try reconnecting with a new session.
        // The data should be persisted, even though the session was not.
        zk = qb.createClient(watcher, hostPorts[entry.getValue()],
                             CONNECTION_TIMEOUT);
        watcher.waitForConnected(CONNECTION_TIMEOUT);

        long newSessionId = zk.getSessionId();
        Assert.assertFalse(newSessionId == localSessionId);

        for (int i = 0; i < 5; i++) {
            Assert.assertNotNull("Data not exists in " + entry.getKey(),
                    zk.exists(nodePrefix + i, null));
        }

        // We may get the correct exception but the txn may go through
        Assert.assertNull("Data exists in " + entry.getKey(),
                zk.exists(nodePrefix + "ephemeral", null));

        zk.close();
    }
    qb.shutdownServers();
}
 
开发者ID:didichuxing2,项目名称:https-github.com-apache-zookeeper,代码行数:63,代码来源:LocalSessionsOnlyTest.java

示例6: expireSession

import org.apache.zookeeper.ZooKeeper; //导入方法依赖的package包/类
/**
 * Expire a ZooKeeper session as recommended in ZooKeeper documentation
 * http://wiki.apache.org/hadoop/ZooKeeper/FAQ#A4
 * There are issues when doing this:
 * [1] http://www.mail-archive.com/[email protected]/msg01942.html
 * [2] https://issues.apache.org/jira/browse/ZOOKEEPER-1105
 *
 * @param nodeZK - the ZK watcher to expire
 * @param checkStatus - true to check if we can create an HTable with the
 *                    current configuration.
 */
public void expireSession(ZooKeeperWatcher nodeZK, boolean checkStatus)
  throws Exception {
  Configuration c = new Configuration(this.conf);
  String quorumServers = ZKConfig.getZKQuorumServersString(c);
  ZooKeeper zk = nodeZK.getRecoverableZooKeeper().getZooKeeper();
  byte[] password = zk.getSessionPasswd();
  long sessionID = zk.getSessionId();

  // Expiry seems to be asynchronous (see comment from P. Hunt in [1]),
  //  so we create a first watcher to be sure that the
  //  event was sent. We expect that if our watcher receives the event
  //  other watchers on the same machine will get is as well.
  // When we ask to close the connection, ZK does not close it before
  //  we receive all the events, so don't have to capture the event, just
  //  closing the connection should be enough.
  ZooKeeper monitor = new ZooKeeper(quorumServers,
    1000, new org.apache.zookeeper.Watcher(){
    @Override
    public void process(WatchedEvent watchedEvent) {
      LOG.info("Monitor ZKW received event="+watchedEvent);
    }
  } , sessionID, password);

  // Making it expire
  ZooKeeper newZK = new ZooKeeper(quorumServers,
      1000, EmptyWatcher.instance, sessionID, password);

  //ensure that we have connection to the server before closing down, otherwise
  //the close session event will be eaten out before we start CONNECTING state
  long start = System.currentTimeMillis();
  while (newZK.getState() != States.CONNECTED
       && System.currentTimeMillis() - start < 1000) {
     Thread.sleep(1);
  }
  newZK.close();
  LOG.info("ZK Closed Session 0x" + Long.toHexString(sessionID));

  // Now closing & waiting to be sure that the clients get it.
  monitor.close();

  if (checkStatus) {
    new HTable(new Configuration(conf), TableName.META_TABLE_NAME).close();
  }
}
 
开发者ID:fengchen8086,项目名称:ditb,代码行数:56,代码来源:HBaseTestingUtility.java


注:本文中的org.apache.zookeeper.ZooKeeper.getSessionId方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。