Exemplo n.º 1
0
  @Test
  public void testNamespace() throws Exception {
    Timing timing = new Timing();
    ChildReaper reaper = null;
    CuratorFramework client =
        CuratorFrameworkFactory.builder()
            .connectString(server.getConnectString())
            .sessionTimeoutMs(timing.session())
            .connectionTimeoutMs(timing.connection())
            .retryPolicy(new RetryOneTime(1))
            .namespace("foo")
            .build();
    try {
      client.start();

      for (int i = 0; i < 10; ++i) {
        client.create().creatingParentsIfNeeded().forPath("/test/" + Integer.toString(i));
      }

      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(), 0);

      stat = client.usingNamespace(null).checkExists().forPath("/foo/test");
      Assert.assertNotNull(stat);
      Assert.assertEquals(stat.getNumChildren(), 0);
    } finally {
      Closeables.closeQuietly(reaper);
      Closeables.closeQuietly(client);
    }
  }
  @Test
  public void testWithNamespace() throws Exception {
    CuratorFramework client =
        CuratorFrameworkFactory.builder()
            .connectString(server.getConnectString())
            .retryPolicy(new RetryOneTime(1))
            .namespace("galt")
            .build();
    client.start();
    try {
      Collection<CuratorTransactionResult> results =
          client
              .inTransaction()
              .create()
              .forPath("/foo", "one".getBytes())
              .and()
              .create()
              .withMode(CreateMode.PERSISTENT_SEQUENTIAL)
              .forPath("/test-", "one".getBytes())
              .and()
              .setData()
              .forPath("/foo", "two".getBytes())
              .and()
              .create()
              .forPath("/foo/bar")
              .and()
              .delete()
              .forPath("/foo/bar")
              .and()
              .commit();

      Assert.assertTrue(client.checkExists().forPath("/foo") != null);
      Assert.assertTrue(client.nonNamespaceView().checkExists().forPath("/galt/foo") != null);
      Assert.assertEquals(client.getData().forPath("/foo"), "two".getBytes());
      Assert.assertTrue(client.checkExists().forPath("/foo/bar") == null);

      CuratorTransactionResult ephemeralResult =
          Iterables.find(
              results, CuratorTransactionResult.ofTypeAndPath(OperationType.CREATE, "/test-"));
      Assert.assertNotNull(ephemeralResult);
      Assert.assertNotEquals(ephemeralResult.getResultPath(), "/test-");
      Assert.assertTrue(ephemeralResult.getResultPath().startsWith("/test-"));
    } finally {
      client.close();
    }
  }
Exemplo n.º 3
0
  private void initZooKeeper() {
    getLogger().info("Init ZooKeeper");
    this.zooKeeperClient =
        CuratorFrameworkFactory.builder()
            .connectString("elab.kr:2181")
            .retryPolicy(new ExponentialBackoffRetry(1000, 3))
            .aclProvider(new ServiceACLProvider())
            .sessionTimeoutMs(10 * 1000)
            .build();
    this.zooKeeperClient.start();
    try {
      this.zooKeeperClient.getZookeeperClient().blockUntilConnectedOrTimedOut();
    } catch (InterruptedException e) {
      getLogger().fatal("Not Connected ZooKeeper", e);
    }

    this.registerService();
  }
  /** Amoeba启动的时候,初始化zookeeper客户端,另外,给zookeeper预热 */
  public void init() throws Exception {

    Properties props = Utils.readGlobalSeqConfigProps();
    String zkHosts = props.getProperty("zkHosts", "127.0.0.1:2181");
    Integer connTimeOut = Integer.valueOf(props.getProperty("zkConnTimeOut", "60"));

    log.info(String.format("zookeeper config: connect string= %s", zkHosts));
    log.info(String.format("zookeeper config: connect timeout= %d seconds", connTimeOut));

    client =
        CuratorFrameworkFactory.builder()
            .connectString(zkHosts)
            .retryPolicy(new ExponentialBackoffRetry(BASE_SLEEP_TIME, RETRY_TIMES))
            .connectionTimeoutMs(connTimeOut * 1000)
            .build(); // 时间要由秒转成毫秒

    client.start();

    // 只是为client热身而调用
    client.checkExists().forPath(ROOT_PATH);
  }
  private void buildZKClient(final String zkFullPath) {
    final String[] zkFullPathItems = zkFullPath.split(ZK_FULL_PATH_DELIMITER);
    zkHost_ = zkFullPathItems[1];
    zkNamespace_ =
        zkFullPathItems[2].substring(
            0, zkFullPathItems[2].lastIndexOf(ZK_FULL_PATH_NAMESPACE_SEPERATOR));
    zkNodePath_ =
        zkFullPathItems[2].substring(
            zkFullPathItems[2].lastIndexOf(ZK_FULL_PATH_NAMESPACE_SEPERATOR));
    if (zkClient_ == null) {
      try {
        zkClient_ =
            CuratorFrameworkFactory.builder()
                .connectString(zkHost_)
                .namespace(zkNamespace_)
                .retryPolicy(new ExponentialBackoffRetry(1000, 60))
                .connectionTimeoutMs(2 * 3600 * 1000)
                .build();
        zkClient_
            .getConnectionStateListenable()
            .addListener(
                new ConnectionStateListener() {

                  @Override
                  public void stateChanged(CuratorFramework client, ConnectionState newState) {
                    // TODO Auto-generated method stub
                    if (newState == ConnectionState.LOST) {
                      try {
                        synchronized (this) {
                          while (!client.getZookeeperClient().blockUntilConnectedOrTimedOut()) {
                            if (logger_ != null) {
                              if (logger_.isInfoEnabled()) logger_.info("waitting reconnected...");
                            }
                            wait(1000);
                          }
                        }
                        if (logger_ != null) {
                          if (logger_.isInfoEnabled()) logger_.info("to zookeeper reconnected.");
                        }
                        doNodesDiscovery();
                      } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        if (logger_ != null) {
                          if (logger_.isInfoEnabled())
                            logger_.info(
                                String.format(
                                    "To re connect to zookeeper to generate an error, cause:%s",
                                    e));
                        }
                      }
                    }
                  }
                });
        zkClient_.start();
      } catch (Throwable t) {
        zkClient_.close();
        throw new IllegalStateException("building zookeeper client failed.");
      }
    }
  }