gpt4 book ai didi

java - Java 中的 Cassandra - 每次都使用相同的集群名称

转载 作者:行者123 更新时间:2023-12-01 10:21:01 24 4
gpt4 key购买 nike

我试图在 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 中遇到输出为

线程“main”中出现异常 com.datastax.driver.core.exceptions.NoHostAvailableException:尝试查询的所有主机均失败(尝试过:[/127.0.0.1])

为什么它甚至拒绝连接,更不用说创建表了? (在 cassandra.yaml 中配置的 9042 端口已打开并且 cassandra 服务正在运行)

2) 为什么在我的代码中,cluster.getClusterName(); 每次都会给出“cluster1”作为集群名称,而不管我在 cassandra.yaml 文件中的集群名称如何?

但是,当我尝试使用以下代码时,它起作用了:

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 :

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 like cluster1 where each Cluster instance in the same JVM will have a different number.

关于java - Java 中的 Cassandra - 每次都使用相同的集群名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35620329/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com