public Session getNewSession() { return cluster.newSession(); }
@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); } }
private ResultSet performQuery(Cluster cluster, String cql) { try (Cluster closeableCluster = cluster) { Session session = closeableCluster.newSession(); return session.execute(cql); } } }
/** * {@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; }
@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(); } }
@Override public Session newSession() { return delegate().newSession(); }
.build(); try { final Session session = cluster.newSession();
@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(); } }
/** * {@inheritDoc} */ @Override public Session newSession() { return new TracingSession(super.newSession(), tracer, querySpanNameProvider, executorService); }
@Override public Session newSession() { return delegate().newSession(); }
@Override public Session newSession() { return delegate().newSession(); }
@Override public Session newSession() { return delegate().newSession(); }
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>
try (Session session = cluster.newSession()) { ResultSet resultSet = session.execute(
/** * {@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; }
@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!"); } } }
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(); }
.build(); try { final Session session = cluster.newSession();
LOG.info(getConnectionInfo(metadata)); session = cluster.newSession(); if (null == keyspace.getName() || keyspace.getName().trim().length() == 0) throw new IllegalArgumentException("Keyspace not specified.");
@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(); } }