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

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

本文整理了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

  1. /**
  2. * Add field use_raw_configuration_schema to endpointProfile that used to support devices using
  3. * SDK version 0.9.0
  4. */
  5. public void transform() {
  6. //mongo
  7. MongoClient client = new MongoClient(host);
  8. MongoDatabase database = client.getDatabase(dbName);
  9. MongoCollection<Document> endpointProfile = database.getCollection("endpoint_profile");
  10. endpointProfile.updateMany(new Document(), eq("$set", eq("use_raw_schema", false)));
  11. //cassandra
  12. Cluster cluster = Cluster.builder().addContactPoint(host).build();
  13. Session session = cluster.connect(dbName);
  14. session.execute("ALTER TABLE ep_profile ADD use_raw_schema boolean");
  15. session.close();
  16. cluster.close();
  17. }
  18. }

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

  1. /**
  2. * Validates that a Cluster that was never able to successfully establish connection a session can
  3. * be closed properly.
  4. *
  5. * @test_category connection
  6. * @expected_result Cluster closes within 1 second.
  7. */
  8. @Test(groups = "short")
  9. public void should_be_able_to_close_cluster_that_never_successfully_connected() throws Exception {
  10. Cluster cluster =
  11. Cluster.builder()
  12. .addContactPointsWithPorts(new InetSocketAddress("127.0.0.1", 65534))
  13. .withNettyOptions(nonQuietClusterCloseOptions)
  14. .build();
  15. try {
  16. cluster.connect();
  17. fail("Should not have been able to connect.");
  18. } catch (NoHostAvailableException e) {
  19. // Expected.
  20. CloseFuture closeFuture = cluster.closeAsync();
  21. try {
  22. closeFuture.get(1, TimeUnit.SECONDS);
  23. } catch (TimeoutException e1) {
  24. fail("Close Future did not complete quickly.");
  25. }
  26. } finally {
  27. cluster.close();
  28. }
  29. }

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

  1. @Override
  2. protected void before() throws Throwable {
  3. dependency.before();
  4. Cluster cluster = Cluster.builder().addContactPoint(getHost()).withPort(getPort())
  5. .withNettyOptions(new NettyOptions() {
  6. @Override
  7. public void onClusterClose(EventLoopGroup eventLoopGroup) {
  8. eventLoopGroup.shutdownGracefully(0, 0, TimeUnit.MILLISECONDS).syncUninterruptibly();
  9. }
  10. }).build();
  11. Session session = cluster.newSession();
  12. try {
  13. if (requiredVersion != null) {
  14. Version cassandraReleaseVersion = CassandraVersion.getReleaseVersion(session);
  15. if (cassandraReleaseVersion.isLessThan(requiredVersion)) {
  16. throw new AssumptionViolatedException(
  17. String.format("Cassandra at %s:%s runs in Version %s but we require at least %s", getHost(), getPort(),
  18. cassandraReleaseVersion, requiredVersion));
  19. }
  20. }
  21. session.execute(String.format("CREATE KEYSPACE IF NOT EXISTS %s \n"
  22. + "WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };", keyspaceName));
  23. } finally {
  24. session.close();
  25. cluster.close();
  26. }
  27. }

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

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

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

  1. private void connectInternal() {
  2. try {
  3. Cluster cluster = config.createBuilder().build();
  4. cassandraSession = cluster.connect(keySpace);
  5. cassandraMetrics = cluster.getMetrics();
  6. connected.set(true);
  7. } catch (Exception e) {
  8. LOGGER.error("Error connection to Cassandra" + e.getMessage());
  9. if (pool != null) {
  10. pool.shutdownNow();
  11. pool = null;
  12. }
  13. if (cassandraSession != null) {
  14. cassandraSession.close();
  15. if (cassandraSession.getCluster() != null)
  16. cassandraSession.getCluster().close();
  17. }
  18. connected.set(false);
  19. }
  20. }

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

  1. /**
  2. * Ensures that if the core connection pool is full that borrowConnection will create and use a
  3. * new connection.
  4. *
  5. * @jira_ticket JAVA-419
  6. * @test_category connection:connection_pool
  7. * @since 2.0.10, 2.1.6
  8. */
  9. @Test(groups = "short")
  10. public void should_add_extra_connection_when_core_full() throws Exception {
  11. Cluster cluster = createClusterBuilder().build();
  12. List<MockRequest> allRequests = newArrayList();
  13. try {
  14. HostConnectionPool pool = createPool(cluster, 1, 2);
  15. Connection.Factory factory = spy(cluster.manager.connectionFactory);
  16. cluster.manager.connectionFactory = factory;
  17. Connection core = pool.connections.get(0);
  18. // Fill core connection + 1
  19. List<MockRequest> requests = MockRequest.sendMany(NEW_CONNECTION_THRESHOLD, pool);
  20. assertBorrowedConnection(requests, core);
  21. allRequests.addAll(requests);
  22. allRequests.add(MockRequest.send(pool));
  23. // Reaching the threshold should have triggered the creation of an extra one
  24. verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
  25. assertPoolSize(pool, 2);
  26. } finally {
  27. MockRequest.completeAll(allRequests);
  28. cluster.close();
  29. }
  30. }

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

  1. /**
  2. * Validates that when a Cluster is initialized that {@link
  3. * SpeculativeExecutionPolicy#init(Cluster)} is called and that when a Cluster is closed {@link
  4. * SpeculativeExecutionPolicy#close()} is called.
  5. *
  6. * @test_category queries:speculative_execution
  7. * @expected_result init and close are called on cluster init and close.
  8. * @jira_ticket JAVA-796
  9. * @since 2.0.11, 2.1.7, 2.2.1
  10. */
  11. @Test(groups = "short")
  12. public void should_init_and_close_policy_on_cluster() {
  13. SpeculativeExecutionPolicy mockPolicy = mock(SpeculativeExecutionPolicy.class);
  14. Cluster cluster =
  15. Cluster.builder()
  16. .addContactPoints(scassandras.address(2).getAddress())
  17. .withPort(scassandras.getBinaryPort())
  18. .withSpeculativeExecutionPolicy(mockPolicy)
  19. .build();
  20. verify(mockPolicy, times(0)).init(cluster);
  21. verify(mockPolicy, times(0)).close();
  22. try {
  23. cluster.init();
  24. verify(mockPolicy, times(1)).init(cluster);
  25. } finally {
  26. cluster.close();
  27. verify(mockPolicy, times(1)).close();
  28. }
  29. }

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

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

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

  1. /**
  2. * Ensures that if a fixed-sized pool has filled its core connections and reached a number of
  3. * requests to cause it to be enqueued, that if the request is not serviced within 100ms, a
  4. * BusyPoolException is raised with a timeout.
  5. *
  6. * @jira_ticket JAVA-1371
  7. * @test_category connection:connection_pool
  8. * @since 3.0.7 3.1.4 3.2.0
  9. */
  10. @Test(groups = "short")
  11. public void should_reject_if_enqueued_and_timeout_reached() {
  12. Cluster cluster = createClusterBuilder().build();
  13. List<MockRequest> allRequests = newArrayList();
  14. try {
  15. HostConnectionPool pool = createPool(cluster, 1, 1);
  16. List<MockRequest> requests = MockRequest.sendMany(128, pool);
  17. allRequests.addAll(requests);
  18. // pool is now full, this request will be enqueued
  19. MockRequest failedBorrow = MockRequest.send(pool, 100, 128);
  20. try {
  21. failedBorrow.getConnection();
  22. fail("Expected a BusyPoolException");
  23. } catch (BusyPoolException e) {
  24. assertThat(e).hasMessageContaining("timed out");
  25. }
  26. } finally {
  27. MockRequest.completeAll(allRequests);
  28. cluster.close();
  29. }
  30. }

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

  1. /**
  2. * When no consistency level is defined the default of LOCAL_ONE should be used.
  3. *
  4. * @test_category consistency
  5. */
  6. @Test(groups = "short")
  7. public void should_use_global_default_cl_when_none_specified() throws Throwable {
  8. // Build a cluster with no CL level set in the query options.
  9. Cluster cluster = builder().build();
  10. try {
  11. Session session = cluster.connect();
  12. // Construct unique simple statement query, with no CL defined.
  13. // Check to ensure
  14. String queryString = "default_cl";
  15. Query clQuery = executeSimple(session, queryString, null, null);
  16. assertTrue(clQuery.getConsistency().equals(ConsistencyLevel.LOCAL_ONE.toString()));
  17. // Check prepared statement default CL
  18. String prepareString = "prepared_default_cl";
  19. PreparedStatementExecution pse = executePrepared(session, prepareString, null, null);
  20. assertTrue(pse.getConsistency().equals(ConsistencyLevel.LOCAL_ONE.toString()));
  21. // Check batch statement default CL
  22. String batchStateString = "batch_default_cl";
  23. BatchExecution batch = executeBatch(session, batchStateString, null, null);
  24. assertTrue(batch.getConsistency().equals(ConsistencyLevel.LOCAL_ONE.toString()));
  25. } finally {
  26. cluster.close();
  27. }
  28. }

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

  1. Cluster cluster = builder().build();
  2. try {
  3. Session session = cluster.connect();
  4. assertTrue(batch.getConsistency().equals(cl.toString()));
  5. } finally {
  6. cluster.close();

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

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

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

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

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

  1. /**
  2. * Ensures that if a connection on a host is lost but other connections remain intact in the Pool
  3. * that the host is not marked down.
  4. *
  5. * @jira_ticket JAVA-544
  6. * @test_category connection:connection_pool
  7. * @since 2.0.11
  8. */
  9. @Test(groups = "short")
  10. public void should_keep_host_up_when_one_connection_lost() throws Exception {
  11. Cluster cluster = createClusterBuilder().build();
  12. try {
  13. HostConnectionPool pool = createPool(cluster, 2, 2);
  14. Connection core0 = pool.connections.get(0);
  15. Connection core1 = pool.connections.get(1);
  16. // Drop a connection and ensure the host stays up.
  17. currentClient.disableListener();
  18. currentClient.closeConnection(CLOSE, ((InetSocketAddress) core0.channel.localAddress()));
  19. Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
  20. // connection 0 should be down, while connection 1 and the Host should remain up.
  21. assertThat(core0.isClosed()).isTrue();
  22. assertThat(core1.isClosed()).isFalse();
  23. assertThat(pool.connections).doesNotContain(core0);
  24. assertThat(cluster).host(1).hasState(Host.State.UP);
  25. assertThat(cluster).hasOpenControlConnection();
  26. } finally {
  27. cluster.close();
  28. }
  29. }

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

  1. @Test(groups = "short")
  2. public void should_count_inflight_requests_metrics() {
  3. sCluster
  4. .node(1)
  5. .primingClient()
  6. .prime(
  7. PrimingRequest.queryBuilder()
  8. .withQuery("mock query")
  9. .withThen(then().withFixedDelay(100000L))
  10. .build());
  11. Cluster cluster = null;
  12. try {
  13. cluster = builder().build();
  14. Session session = cluster.connect();
  15. assertThat(cluster.getMetrics().getInFlightRequests().getValue()).isEqualTo(0);
  16. session.executeAsync("mock query");
  17. session.executeAsync("mock query");
  18. assertThat(cluster.getMetrics().getInFlightRequests().getValue()).isEqualTo(2);
  19. } finally {
  20. if (cluster != null) {
  21. cluster.close();
  22. }
  23. }
  24. }

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

  1. @Test(groups = "short")
  2. public void should_countdown_inflight_requests_metrics() {
  3. sCluster
  4. .node(1)
  5. .primingClient()
  6. .prime(PrimingRequest.queryBuilder().withQuery("mock query").withThen(then()).build());
  7. Cluster cluster = null;
  8. try {
  9. cluster = builder().build();
  10. Session session = cluster.connect();
  11. assertThat(cluster.getMetrics().getInFlightRequests().getValue()).isEqualTo(0);
  12. session.executeAsync("mock query").getUninterruptibly();
  13. session.executeAsync("mock query").getUninterruptibly();
  14. assertThat(cluster.getMetrics().getInFlightRequests().getValue()).isEqualTo(0);
  15. } finally {
  16. if (cluster != null) {
  17. cluster.close();
  18. }
  19. }
  20. }
  21. }

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

  1. private void deleteNode2RpcAddressFromNode1() throws Exception {
  2. InetSocketAddress firstHost = ccm().addressOfNode(1);
  3. Cluster cluster =
  4. register(
  5. Cluster.builder()
  6. .addContactPoints(firstHost.getAddress())
  7. .withPort(ccm().getBinaryPort())
  8. // ensure we will only connect to node1
  9. .withLoadBalancingPolicy(
  10. new WhiteListPolicy(
  11. Policies.defaultLoadBalancingPolicy(), Lists.newArrayList(firstHost)))
  12. .build());
  13. Session session = cluster.connect();
  14. String deleteStmt =
  15. String.format(
  16. "DELETE rpc_address FROM system.peers WHERE peer = '%s'",
  17. ccm().addressOfNode(2).getHostName());
  18. session.execute(deleteStmt);
  19. session.close();
  20. cluster.close();
  21. }
  22. }

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

  1. public void useNamedValuesWithProtocol(ProtocolVersion version) {
  2. Cluster vCluster =
  3. createClusterBuilder()
  4. .addContactPoints(getContactPoints())
  5. .withPort(ccm().getBinaryPort())
  6. .withProtocolVersion(version)
  7. .build();
  8. try {
  9. Session vSession = vCluster.connect(this.keyspace);
  10. // Given - A simple statement with named parameters.
  11. SimpleStatement statement =
  12. new SimpleStatement(
  13. "SELECT * FROM users WHERE id = :id", ImmutableMap.<String, Object>of("id", 1));
  14. // When - Executing that statement against a Cluster instance using Protocol Version V2.
  15. vSession.execute(statement).one();
  16. // Then - Should throw an UnsupportedFeatureException
  17. } finally {
  18. vCluster.close();
  19. }
  20. }

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

  1. .withPort(sCluster.getBinaryPort())
  2. .withLoadBalancingPolicy(policy)
  3. .build();
  4. cluster.close();
  5. sCluster.stop();

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

  1. .addContactPointsWithPorts(new InetSocketAddress("127.0.0.1", 65534))
  2. .withNettyOptions(nonQuietClusterCloseOptions)
  3. .build();
  4. try {
  5. cluster.connect();
  6. cluster.close();

相关文章