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

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

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

Cluster.newSession介绍

[英]Creates a new session on this cluster but does not initialize it.

Because this method does not perform any initialization, it cannot fail. The initialization of the session (the connection of the Session to the Cassandra nodes) will occur if either the Session#init method is called explicitly, or whenever the returned session object is used.

Once a session returned by this method gets initialized (see above), it will be set to no keyspace. If you want to set such session to a keyspace, you will have to explicitly execute a 'USE mykeyspace' query.

Note that if you do not particularly need to defer initialization, it is simpler to use one of the connect() method of this class.
[中]在此群集上创建新会话,但不初始化它。
由于此方法不执行任何初始化,因此不会失败。如果显式调用session#init方法,或者使用返回的session对象,则会初始化会话(会话与Cassandra节点的连接)。
一旦此方法返回的会话被初始化(见上文),它将被设置为无键空间。如果要将此类会话设置为键空间,则必须显式执行“USE mykeyspace”查询。
请注意,如果不特别需要延迟初始化,则使用此类的connect()方法更简单。

代码示例

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

public Session getNewSession() {
 return cluster.newSession();
}

代码示例来源:origin: testcontainers/testcontainers-java

@Override
protected Session createNewConnection() {
  try {
    return CassandraContainer.getCluster(container)
        .newSession();
  } catch (DriverException e) {
    log.error("Could not obtain cassandra connection");
    throw new ConnectionCreationException("Could not obtain cassandra connection", e);
  }
}

代码示例来源:origin: testcontainers/testcontainers-java

private ResultSet performQuery(Cluster cluster, String cql) {
    try (Cluster closeableCluster = cluster) {
      Session session = closeableCluster.newSession();
      return session.execute(cql);
    }
  }
}

代码示例来源:origin: apache/storm

/**
 * {@inheritDoc}
 */
@Override
public synchronized Session connect() throws NoHostAvailableException {
  if (isDisconnected()) {
    LOG.info("Connected to cluster: {}", cluster.getClusterName());
    for (Host host : getAllHosts())
      LOG.info("Datacenter: {}; Host: {}; Rack: {}", host.getDatacenter(), host.getAddress(), host.getRack());
    LOG.info("Connect to cluster using keyspace %s", keyspace);
    session = cluster.connect(keyspace);
  } else {
    LOG.warn("{} - Already connected to cluster: {}", getExecutorName(), cluster.getClusterName());
  }
  if (session.isClosed()) {
    LOG.warn("Session has been closed - create new one!");
    this.session = cluster.newSession();
  }
  return session;
}

代码示例来源: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: com.datastax.cassandra/cassandra-driver-core

@Override
public Session newSession() {
 return delegate().newSession();
}

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

.build();
try {
 final Session session = cluster.newSession();

代码示例来源: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: io.opentracing.contrib/opentracing-cassandra-driver

/**
 * {@inheritDoc}
 */
@Override
public Session newSession() {
 return new TracingSession(super.newSession(), tracer, querySpanNameProvider, executorService);
}

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

@Override
public Session newSession() {
  return delegate().newSession();
}

代码示例来源:origin: io.prestosql.cassandra/cassandra-driver

@Override
public Session newSession() {
  return delegate().newSession();
}

代码示例来源:origin: com.facebook.presto.cassandra/cassandra-driver

@Override
public Session newSession() {
  return delegate().newSession();
}

代码示例来源:origin: stackoverflow.com

String query = "INSERT INTO test.l4_temp1 (id, secidd, val) VALUES (?, ?, ?)";

  Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1")
      .build();
  Session session = cluster.newSession();

  PreparedStatement stmt = session.prepare(query);

  Integer[][] columns = { { 1, 10, 200 }, { 2, 20, 2500 }, { 3, 20, 2567 },
      { 4, 30, 256 }, { 5, 40, 2432 } };

  for (int i = 0; i < columns.length; i++) {
    session.execute(stmt.bind(new Integer[] { columns[i][0], columns[i][1],
        columns[i][0] }));

  }
  session.close();

Maven Dependency
<dependency>
  <groupId>com.datastax.cassandra</groupId>
  <artifactId>cassandra-driver-core</artifactId>
  <version>2.1.0</version>
</dependency>

代码示例来源:origin: org.apache.beam/beam-sdks-java-io-cassandra

try (Session session = cluster.newSession()) {
 ResultSet resultSet =
   session.execute(

代码示例来源:origin: org.apache.storm/storm-cassandra

/**
 * {@inheritDoc}
 */
@Override
public synchronized Session connect() throws NoHostAvailableException {
  if (isDisconnected()) {
    LOG.info("Connected to cluster: {}", cluster.getClusterName());
    for (Host host : getAllHosts())
      LOG.info("Datacenter: {}; Host: {}; Rack: {}", host.getDatacenter(), host.getAddress(), host.getRack());
    LOG.info("Connect to cluster using keyspace %s", keyspace);
    session = cluster.connect(keyspace);
  } else {
    LOG.warn("{} - Already connected to cluster: {}", getExecutorName(), cluster.getClusterName());
  }
  if (session.isClosed()) {
    LOG.warn("Session has been closed - create new one!");
    this.session = cluster.newSession();
  }
  return session;
}

代码示例来源:origin: com.savoirtech.hecate/hecate-test

@Override
  public void evaluate() throws Throwable {
    EmbeddedCassandraServerHelper.startEmbeddedCassandra(cassandra.timeout());
    EmbeddedCassandraServerHelper.cleanEmbeddedCassandra();
    Cluster cluster = Cluster.builder().addContactPoint("localhost").withPort(cassandra.port()).build();
    try (Session tempSession = cluster.newSession()) {
      if (logger.isDebugEnabled()) {
        logger.debug("Creating keyspace {}...", cassandra.keyspace());
      }
      tempSession.execute(String.format("CREATE KEYSPACE IF NOT EXISTS %s WITH replication = {'class':'SimpleStrategy', 'replication_factor':1};", cassandra.keyspace()));
      if (logger.isDebugEnabled()) {
        logger.debug("Keyspace {} created successfully.", cassandra.keyspace());
      }
    }
    session = cluster.connect(cassandra.keyspace());
    try {
      final long before = System.currentTimeMillis();
      inner.evaluate();
      logger.debug("{}(): {} ms", method.getName(), System.currentTimeMillis() - before);
    } finally {
      logger.debug("Closing session...");
      session.close();
      logger.debug("Closing cluster...");
      cluster.close();
      logger.debug("Cassandra shut down complete!");
    }
  }
}

代码示例来源:origin: com.att.nsa/nsaServerLibrary

public CassandraAuthDb(List<String> contactPoints, int port) {
  
  this.contactPoints = new ArrayList<InetAddress> (contactPoints.size());
  
  for (String contactPoint : contactPoints) {
    try {
      this.contactPoints.add(InetAddress.getByName(contactPoint));
    } catch (UnknownHostException e) {
      throw new IllegalArgumentException(e.getMessage());
    }
  }
  
  this.port = port;
  
  cluster = (new Cluster.Builder()).withPort (this.port)
      .addContactPoints(this.contactPoints)
      .withSocketOptions(new SocketOptions().setReadTimeoutMillis(60000).setKeepAlive(true).setReuseAddress(true))
      .withLoadBalancingPolicy(new RoundRobinPolicy())
      .withReconnectionPolicy(new ConstantReconnectionPolicy(500L))
      .withQueryOptions(new QueryOptions().setConsistencyLevel(ConsistencyLevel.ONE))
      .build ();
  
  session = cluster.newSession();
  preparedStatements = new ConcurrentHashMap<StatementName, PreparedStatement> ();
  prepareStatementCreateLock = new Object();
}

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

.build();
try {
 final Session session = cluster.newSession();

代码示例来源:origin: Contrast-Security-OSS/cassandra-migration

LOG.info(getConnectionInfo(metadata));
session = cluster.newSession();
if (null == keyspace.getName() || keyspace.getName().trim().length() == 0)
  throw new IllegalArgumentException("Keyspace not specified.");

代码示例来源:origin: com.datastax.dse/dse-java-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();
 }
}

相关文章