我试图在eclipse中编写一个基本的Java程序,该程序使用Cassandra Java驱动程序连接到Cassandra节点。
我发现此存储库https://github.com/datastax/java-driver。
当我尝试使用-
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)在eclipse中遇到的输出为
线程“主”中的异常com.datastax.driver.core.exceptions.NoHostAvailableException:所有尝试查询的主机均失败(尝试:[/127.0.0.1])
为什么它甚至拒绝连接,更不用说创建表了? (在cassandra.yaml中配置的9042端口已打开,并且cassandra服务正在运行)
2)为什么在我的代码中cluster.getClusterName();不管我在cassandra.yaml文件中的群集名称是什么,每次都给“ cluster1”作为群集名称?
但是,当我尝试使用以下代码时,它起作用了:
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();
}
这两种方法之间的逻辑区别是什么?
最佳答案
我认为您指的是Cluster.getClusterName()
。从the javadoc:
请注意,这不是Cassandra群集名称,而是分配给此Cluster对象的名称。当前,该名称仅用于一个目的:当多个Cluster实例驻留在同一JVM中时,以区分公开的JMX度量标准(首先应该很少出现)。该名称可以在群集构建时设置(例如,通过Cluster.Builder.withClusterName(java.lang.String)
设置),但默认名称为cluster1
之类的名称,其中同一JVM中的每个群集实例将具有不同的编号。