我正在尝试创建一个简单的java应用程序,它可以连接到在本地机器上运行的docker容器中运行的cassandra。为了我的生命,我不能让它连接到容器!
我要这样启动我的容器。
docker run -p 9042:9042 cassandra:latest
我的java代码并不是很花哨。。
private Cluster cluster;
private Session session;
String serverIP = "localhost";
String username = "cassandra";
String password = "cassandra";
String keyspace = "DefaultKeyspace";
public static void main(String[] args) {
CassandraTest cassandraTest = new CassandraTest();
cassandraTest.connect("localhost");
}
public void connect(String node) {
try {
String username = "cassandra";
String password = "cassandra";
String keyspace = "DefaultKeyspace";
cluster = Cluster.builder()
.addContactPoints(serverIP).withCredentials(username.trim(), password.trim())
.build();
session = cluster.connect(keyspace);
// createSchema();
Metadata metadata = cluster.getMetadata();
System.out.println("Connected to cluster:" + metadata.getClusterName());
for (Host host : metadata.getAllHosts()) {
System.out.println("Datatacenter: " + host.getDatacenter()
+ "; Host: " + host.getAddress() + "; Rack: "
+ host.getRack());
}
} catch (Exception e) {
e.printStackTrace();
}
getSession();
createSchema();
}
但我不知道我该怎么做,我一直得到这个。。
com.datastax.driver.core.exceptions.NoHostAvailableException: All host(s) tried for query failed (tried: localhost/127.0.0.1:9042 (com.datastax.driver.core.exceptions.InvalidQueryException: unconfigured table schema_keyspaces))
at com.datastax.driver.core.ControlConnection.reconnectInternal(ControlConnection.java:220)
at com.datastax.driver.core.ControlConnection.connect(ControlConnection.java:78)
at com.datastax.driver.core.Cluster$Manager.init(Cluster.java:1231)
at com.datastax.driver.core.Cluster.init(Cluster.java:158)
at com.datastax.driver.core.Cluster.connect(Cluster.java:246)
at com.datastax.driver.core.Cluster.connect(Cluster.java:279)
at CassandraTest.connect(CassandraTest.java:37)
at CassandraTest.main(CassandraTest.java:27)
Exception in thread "main" java.lang.IllegalStateException: Can't use this Cluster instance because it was previously closed
at com.datastax.driver.core.Cluster$Manager.init(Cluster.java:1213)
at com.datastax.driver.core.Cluster.init(Cluster.java:158)
at com.datastax.driver.core.Cluster.connect(Cluster.java:246)
at CassandraTest.getSession(CassandraTest.java:56)
at CassandraTest.connect(CassandraTest.java:51)
at CassandraTest.main(CassandraTest.java:27)
我也尝试过使用docker主机ip。如何连接??
1条答案
按热度按时间mqkwyuun1#
您需要使用docker机器的ip地址作为cassandra主机。如果cassandra已经清白了,您应该能够使用docker机器ip地址进入它。
因此,在代码中,不要使用localhost,而是尝试使用docker机器ip