Reputation: 1
I was trying to write a basic java program in eclipse that uses Cassandra java driver to connect to a Cassandra node.
I found this repository https://github.com/datastax/java-driver.
When I tried to run using -
package com.example.cassandra;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.Host;
public class SampleConnection {
private Cluster cluster;
private Session session;
public void connect(String node){
cluster = Cluster.builder().addContactPoint(node).build();
session = cluster.connect("mykeyspace");
System.out.println(cluster.getClusterName());
}
public void close()
{
cluster.shutdown();
}
public static void main(String args[]) {
SampleConnection client = new SampleConnection();
client.connect("127.0.0.1");
client.close();
}
1) Encountered output in eclipse as
Exception in thread "main" com.datastax.driver.core.exceptions.NoHostAvailableException: All host(s) tried for query failed (tried: [/127.0.0.1])
Why it is refusing even to connect let alone create a table? (9042 port, configured in cassandra.yaml, is open & cassandra service is running)
2) Why, in my code, cluster.getClusterName(); is giving "cluster1" as cluster name everytime regardless of my cluster name in cassandra.yaml file?
However, when I tried to use the below code, it worked:
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Host;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.policies.DefaultRetryPolicy;
public class CassConnector {
private static Cluster cluster;
private static Session session;
public static Cluster connect(String node) {
return Cluster.builder().addContactPoint(node)
.withRetryPolicy(DefaultRetryPolicy.INSTANCE).build();
}
public static void main(String[] arg) {
cluster = connect("localhost");
session = cluster.connect("mykeyspace");
session.execute("CREATE KEYSPACE myks WITH REPLICATION = "
+ "{ 'class' : 'SimpleStrategy', 'replication_factor' : 1};" );
session.execute("USE mykeyspace");
String query = "CREATE TABLE emp(emp_id int PRIMARY KEY, "
+ "emp_name text, "
+ "emp_city text );";
session.execute(query);
System.out.println("Table created!");
session.close();
cluster.close();
}
What's the logical difference between these two approaches?
Upvotes: 0
Views: 539
Reputation: 2312
I assume you're referring to Cluster.getClusterName()
. From the javadoc:
Note that this is not the Cassandra cluster name, but rather a name assigned to this Cluster object. Currently, that name is only used for one purpose: to distinguish exposed JMX metrics when multiple Cluster instances live in the same JVM (which should be rare in the first place). That name can be set at Cluster building time (through
Cluster.Builder.withClusterName(java.lang.String)
for instance) but will default to a name likecluster1
where each Cluster instance in the same JVM will have a different number.
Upvotes: 1