com.datastax.driver.core.Cluster.close()方法的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(13.3k)|赞(0)|评价(0)|浏览(128)

本文整理了Java中com.datastax.driver.core.Cluster.close()方法的一些代码示例,展示了Cluster.close()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Cluster.close()方法的具体详情如下:
包路径:com.datastax.driver.core.Cluster
类名称:Cluster
方法名:close

Cluster.close介绍

[英]Initiates a shutdown of this cluster instance and blocks until that shutdown completes.

This method is a shortcut for closeAsync().get().
[中]启动此群集实例的关闭并阻止,直到关闭完成。
此方法是closeAsync()的快捷方式。get()。

代码示例

代码示例来源:origin: kaaproject/kaa

/**
  * Add field use_raw_configuration_schema to endpointProfile that used to support devices using
  * SDK version 0.9.0
  */
 public void transform() {
  //mongo
  MongoClient client = new MongoClient(host);
  MongoDatabase database = client.getDatabase(dbName);
  MongoCollection<Document> endpointProfile = database.getCollection("endpoint_profile");
  endpointProfile.updateMany(new Document(), eq("$set", eq("use_raw_schema", false)));

  //cassandra
  Cluster cluster = Cluster.builder().addContactPoint(host).build();
  Session session = cluster.connect(dbName);
  session.execute("ALTER TABLE ep_profile ADD use_raw_schema boolean");
  session.close();
  cluster.close();

 }
}

代码示例来源:origin: com.datastax.cassandra/cassandra-driver-core

/**
 * Validates that a Cluster that was never able to successfully establish connection a session can
 * be closed properly.
 *
 * @test_category connection
 * @expected_result Cluster closes within 1 second.
 */
@Test(groups = "short")
public void should_be_able_to_close_cluster_that_never_successfully_connected() throws Exception {
 Cluster cluster =
   Cluster.builder()
     .addContactPointsWithPorts(new InetSocketAddress("127.0.0.1", 65534))
     .withNettyOptions(nonQuietClusterCloseOptions)
     .build();
 try {
  cluster.connect();
  fail("Should not have been able to connect.");
 } catch (NoHostAvailableException e) {
  // Expected.
  CloseFuture closeFuture = cluster.closeAsync();
  try {
   closeFuture.get(1, TimeUnit.SECONDS);
  } catch (TimeoutException e1) {
   fail("Close Future did not complete quickly.");
  }
 } finally {
  cluster.close();
 }
}

代码示例来源:origin: spring-projects/spring-data-examples

@Override
protected void before() throws Throwable {
  dependency.before();
  Cluster cluster = Cluster.builder().addContactPoint(getHost()).withPort(getPort())
      .withNettyOptions(new NettyOptions() {
        @Override
        public void onClusterClose(EventLoopGroup eventLoopGroup) {
          eventLoopGroup.shutdownGracefully(0, 0, TimeUnit.MILLISECONDS).syncUninterruptibly();
        }
      }).build();
  Session session = cluster.newSession();
  try {
    if (requiredVersion != null) {
      Version cassandraReleaseVersion = CassandraVersion.getReleaseVersion(session);
      if (cassandraReleaseVersion.isLessThan(requiredVersion)) {
        throw new AssumptionViolatedException(
            String.format("Cassandra at %s:%s runs in Version %s but we require at least %s", getHost(), getPort(),
                cassandraReleaseVersion, requiredVersion));
      }
    }
    session.execute(String.format("CREATE KEYSPACE IF NOT EXISTS %s \n"
        + "WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };", keyspaceName));
  } finally {
    session.close();
    cluster.close();
  }
}

代码示例来源:origin: jooby-project/jooby

Cluster cluster = builder.build();
   .onFailure(x -> log.error("session.close() resulted in exception", x));
 cluster.close();

代码示例来源:origin: pulsarIO/realtime-analytics

private void connectInternal() {
  try {
    Cluster cluster = config.createBuilder().build();
    cassandraSession = cluster.connect(keySpace);
    cassandraMetrics = cluster.getMetrics();
    connected.set(true);
  } catch (Exception e) {
    LOGGER.error("Error connection to Cassandra" + e.getMessage());
    if (pool != null) {
      pool.shutdownNow();
      pool = null;
    }
    if (cassandraSession != null) {
      cassandraSession.close();
      if (cassandraSession.getCluster() != null)
        cassandraSession.getCluster().close();
    }
    connected.set(false);
  }
}

代码示例来源:origin: com.datastax.cassandra/cassandra-driver-core

/**
 * Ensures that if the core connection pool is full that borrowConnection will create and use a
 * new connection.
 *
 * @jira_ticket JAVA-419
 * @test_category connection:connection_pool
 * @since 2.0.10, 2.1.6
 */
@Test(groups = "short")
public void should_add_extra_connection_when_core_full() throws Exception {
 Cluster cluster = createClusterBuilder().build();
 List<MockRequest> allRequests = newArrayList();
 try {
  HostConnectionPool pool = createPool(cluster, 1, 2);
  Connection.Factory factory = spy(cluster.manager.connectionFactory);
  cluster.manager.connectionFactory = factory;
  Connection core = pool.connections.get(0);
  // Fill core connection + 1
  List<MockRequest> requests = MockRequest.sendMany(NEW_CONNECTION_THRESHOLD, pool);
  assertBorrowedConnection(requests, core);
  allRequests.addAll(requests);
  allRequests.add(MockRequest.send(pool));
  // Reaching the threshold should have triggered the creation of an extra one
  verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
  assertPoolSize(pool, 2);
 } finally {
  MockRequest.completeAll(allRequests);
  cluster.close();
 }
}

代码示例来源:origin: com.datastax.cassandra/cassandra-driver-core

/**
 * Validates that when a Cluster is initialized that {@link
 * SpeculativeExecutionPolicy#init(Cluster)} is called and that when a Cluster is closed {@link
 * SpeculativeExecutionPolicy#close()} is called.
 *
 * @test_category queries:speculative_execution
 * @expected_result init and close are called on cluster init and close.
 * @jira_ticket JAVA-796
 * @since 2.0.11, 2.1.7, 2.2.1
 */
@Test(groups = "short")
public void should_init_and_close_policy_on_cluster() {
 SpeculativeExecutionPolicy mockPolicy = mock(SpeculativeExecutionPolicy.class);
 Cluster cluster =
   Cluster.builder()
     .addContactPoints(scassandras.address(2).getAddress())
     .withPort(scassandras.getBinaryPort())
     .withSpeculativeExecutionPolicy(mockPolicy)
     .build();
 verify(mockPolicy, times(0)).init(cluster);
 verify(mockPolicy, times(0)).close();
 try {
  cluster.init();
  verify(mockPolicy, times(1)).init(cluster);
 } finally {
  cluster.close();
  verify(mockPolicy, times(1)).close();
 }
}

代码示例来源:origin: com.datastax.cassandra/cassandra-driver-core

Cluster cluster = createClusterBuilder().build();
List<MockRequest> allRequests = newArrayList();
try {
 cluster.close();

代码示例来源:origin: com.datastax.cassandra/cassandra-driver-core

/**
 * Ensures that if a fixed-sized pool has filled its core connections and reached a number of
 * requests to cause it to be enqueued, that if the request is not serviced within 100ms, a
 * BusyPoolException is raised with a timeout.
 *
 * @jira_ticket JAVA-1371
 * @test_category connection:connection_pool
 * @since 3.0.7 3.1.4 3.2.0
 */
@Test(groups = "short")
public void should_reject_if_enqueued_and_timeout_reached() {
 Cluster cluster = createClusterBuilder().build();
 List<MockRequest> allRequests = newArrayList();
 try {
  HostConnectionPool pool = createPool(cluster, 1, 1);
  List<MockRequest> requests = MockRequest.sendMany(128, pool);
  allRequests.addAll(requests);
  // pool is now full, this request will be enqueued
  MockRequest failedBorrow = MockRequest.send(pool, 100, 128);
  try {
   failedBorrow.getConnection();
   fail("Expected a BusyPoolException");
  } catch (BusyPoolException e) {
   assertThat(e).hasMessageContaining("timed out");
  }
 } finally {
  MockRequest.completeAll(allRequests);
  cluster.close();
 }
}

代码示例来源:origin: com.datastax.cassandra/cassandra-driver-core

/**
 * When no consistency level is defined the default of LOCAL_ONE should be used.
 *
 * @test_category consistency
 */
@Test(groups = "short")
public void should_use_global_default_cl_when_none_specified() throws Throwable {
 // Build a cluster with no CL level set in the query options.
 Cluster cluster = builder().build();
 try {
  Session session = cluster.connect();
  // Construct unique simple statement query, with no CL defined.
  // Check to ensure
  String queryString = "default_cl";
  Query clQuery = executeSimple(session, queryString, null, null);
  assertTrue(clQuery.getConsistency().equals(ConsistencyLevel.LOCAL_ONE.toString()));
  // Check prepared statement default CL
  String prepareString = "prepared_default_cl";
  PreparedStatementExecution pse = executePrepared(session, prepareString, null, null);
  assertTrue(pse.getConsistency().equals(ConsistencyLevel.LOCAL_ONE.toString()));
  // Check batch statement default CL
  String batchStateString = "batch_default_cl";
  BatchExecution batch = executeBatch(session, batchStateString, null, null);
  assertTrue(batch.getConsistency().equals(ConsistencyLevel.LOCAL_ONE.toString()));
 } finally {
  cluster.close();
 }
}

代码示例来源:origin: com.datastax.cassandra/cassandra-driver-core

Cluster cluster = builder().build();
try {
 Session session = cluster.connect();
 assertTrue(batch.getConsistency().equals(cl.toString()));
} finally {
 cluster.close();

代码示例来源:origin: com.datastax.cassandra/cassandra-driver-core

@Test(groups = "short")
public void should_init_cluster_and_session_if_needed() throws Exception {
 // For this test we need an uninitialized cluster, so we can't reuse the one provided by the
 // parent class. Rebuild a new one with the same (unique) host.
 Host host = cluster().getMetadata().allHosts().iterator().next();
 Cluster cluster2 =
   register(
     Cluster.builder()
       .addContactPointsWithPorts(Lists.newArrayList(host.getSocketAddress()))
       .build());
 try {
  Session session2 = cluster2.newSession();
  // Neither cluster2 nor session2 are initialized at this point
  assertThat(cluster2.manager.metadata).isNull();
  ResultSetFuture future = session2.executeAsync("select release_version from system.local");
  Row row = Uninterruptibles.getUninterruptibly(future).one();
  assertThat(row.getString(0)).isNotEmpty();
 } finally {
  cluster2.close();
 }
}

代码示例来源:origin: com.datastax.cassandra/cassandra-driver-core

builder().withQueryOptions(new QueryOptions().setConsistencyLevel(cl)).build();
try {
 Session session = cluster.connect();
 assertTrue(batch.getConsistency().equals(cl.toString()));
} finally {
 cluster.close();

代码示例来源:origin: com.datastax.cassandra/cassandra-driver-core

/**
 * Ensures that if a connection on a host is lost but other connections remain intact in the Pool
 * that the host is not marked down.
 *
 * @jira_ticket JAVA-544
 * @test_category connection:connection_pool
 * @since 2.0.11
 */
@Test(groups = "short")
public void should_keep_host_up_when_one_connection_lost() throws Exception {
 Cluster cluster = createClusterBuilder().build();
 try {
  HostConnectionPool pool = createPool(cluster, 2, 2);
  Connection core0 = pool.connections.get(0);
  Connection core1 = pool.connections.get(1);
  // Drop a connection and ensure the host stays up.
  currentClient.disableListener();
  currentClient.closeConnection(CLOSE, ((InetSocketAddress) core0.channel.localAddress()));
  Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
  // connection 0 should be down, while connection 1 and the Host should remain up.
  assertThat(core0.isClosed()).isTrue();
  assertThat(core1.isClosed()).isFalse();
  assertThat(pool.connections).doesNotContain(core0);
  assertThat(cluster).host(1).hasState(Host.State.UP);
  assertThat(cluster).hasOpenControlConnection();
 } finally {
  cluster.close();
 }
}

代码示例来源:origin: com.datastax.cassandra/cassandra-driver-core

@Test(groups = "short")
public void should_count_inflight_requests_metrics() {
 sCluster
   .node(1)
   .primingClient()
   .prime(
     PrimingRequest.queryBuilder()
       .withQuery("mock query")
       .withThen(then().withFixedDelay(100000L))
       .build());
 Cluster cluster = null;
 try {
  cluster = builder().build();
  Session session = cluster.connect();
  assertThat(cluster.getMetrics().getInFlightRequests().getValue()).isEqualTo(0);
  session.executeAsync("mock query");
  session.executeAsync("mock query");
  assertThat(cluster.getMetrics().getInFlightRequests().getValue()).isEqualTo(2);
 } finally {
  if (cluster != null) {
   cluster.close();
  }
 }
}

代码示例来源:origin: com.datastax.cassandra/cassandra-driver-core

@Test(groups = "short")
 public void should_countdown_inflight_requests_metrics() {
  sCluster
    .node(1)
    .primingClient()
    .prime(PrimingRequest.queryBuilder().withQuery("mock query").withThen(then()).build());

  Cluster cluster = null;
  try {
   cluster = builder().build();
   Session session = cluster.connect();

   assertThat(cluster.getMetrics().getInFlightRequests().getValue()).isEqualTo(0);
   session.executeAsync("mock query").getUninterruptibly();
   session.executeAsync("mock query").getUninterruptibly();
   assertThat(cluster.getMetrics().getInFlightRequests().getValue()).isEqualTo(0);

  } finally {
   if (cluster != null) {
    cluster.close();
   }
  }
 }
}

代码示例来源:origin: com.datastax.cassandra/cassandra-driver-core

private void deleteNode2RpcAddressFromNode1() throws Exception {
  InetSocketAddress firstHost = ccm().addressOfNode(1);
  Cluster cluster =
    register(
      Cluster.builder()
        .addContactPoints(firstHost.getAddress())
        .withPort(ccm().getBinaryPort())
        // ensure we will only connect to node1
        .withLoadBalancingPolicy(
          new WhiteListPolicy(
            Policies.defaultLoadBalancingPolicy(), Lists.newArrayList(firstHost)))
        .build());
  Session session = cluster.connect();
  String deleteStmt =
    String.format(
      "DELETE rpc_address FROM system.peers WHERE peer = '%s'",
      ccm().addressOfNode(2).getHostName());
  session.execute(deleteStmt);
  session.close();
  cluster.close();
 }
}

代码示例来源:origin: com.datastax.cassandra/cassandra-driver-core

public void useNamedValuesWithProtocol(ProtocolVersion version) {
 Cluster vCluster =
   createClusterBuilder()
     .addContactPoints(getContactPoints())
     .withPort(ccm().getBinaryPort())
     .withProtocolVersion(version)
     .build();
 try {
  Session vSession = vCluster.connect(this.keyspace);
  // Given - A simple statement with named parameters.
  SimpleStatement statement =
    new SimpleStatement(
      "SELECT * FROM users WHERE id = :id", ImmutableMap.<String, Object>of("id", 1));
  // When - Executing that statement against a Cluster instance using Protocol Version V2.
  vSession.execute(statement).one();
  // Then - Should throw an UnsupportedFeatureException
 } finally {
  vCluster.close();
 }
}

代码示例来源:origin: com.datastax.cassandra/cassandra-driver-core

.withPort(sCluster.getBinaryPort())
   .withLoadBalancingPolicy(policy)
   .build();
cluster.close();
sCluster.stop();

代码示例来源:origin: com.datastax.cassandra/cassandra-driver-core

.addContactPointsWithPorts(new InetSocketAddress("127.0.0.1", 65534))
    .withNettyOptions(nonQuietClusterCloseOptions)
    .build();
try {
 cluster.connect();
 cluster.close();

相关文章