cassandra Connecting to Cassandra Java: Connect to a Local Cassandra Instance


Example

Connecting to Cassandra is very similar to connecting to other datasources. With Cassandra, credentials are not required.

String cassandraIPAddress = "127.0.0.1";
String cassandraKeyspace = "myKeyspace";
String username = "foo";
String password = "bar";

com.datastax.driver.core.Cluster cluster = Cluster.builder()
    .addContactPoint(cassandraIPAddress)
    .withCredentials(username, password) // If you have setup a username and password for your node.
    .build();

com.datastax.driver.core.Session session = cluster.connect(cassandraKeyspace);

com.datastax.driver.core.Metadata metadata = cluster.getMetadata();

// Output Cassandra connection status
System.out.println("Connected to Cassandra cluster: " + metadata.getClusterName() + " with Partitioner: " + metadata.getPartitioner());

// Loop through your entire Cluster.
for (Host host : metadata.getAllHosts()) {
    System.out.println("Cassandra Host Address: " + host.getAddress() + " | Is Up = " + host.isUp());
}