我在 Eclipse 中有一段代码,我已成功建立了 cassandra 连接。连接已成功完成,但我看到 Eclipse 中的大红色按钮仍然亮着,即该过程尚未完成。我想关闭红色按钮作为正常代码的执行 做。这是我的代码...
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Host;
import com.datastax.driver.core.Metadata;
public class MyConnection{
private Cluster cluster;
public void connect(String node) {
cluster = Cluster.builder().addContactPoint(node).build();
Metadata metadata = cluster.getMetadata();
System.out.println("Cassandra connection established");
System.out.printf("Connected to cluster: %s\n",
metadata.getClusterName());
for (Host host : metadata.getAllHosts()) {
System.out.printf("Datatacenter: %s; Host: %s; Rack: %s \n",
host.getDatacenter(), host.getAddress(), host.getRack());
}
}
public void close() {
cluster.shutdown();
}
public static void main(String[] args) {
MyConnection c = new MyConnection();
c.connect("127.0.0.1");
c.close();
}
}
这是代码。请有人帮忙..
最佳答案
不太确定 eclips 正在做什么,但运行了相同的代码 (slightly modified)在 intelliJ 中并且该过程自行完成,以下是输出:
log4j:WARN No appenders could be found for logger (com.datastax.driver.core.ControlConnection).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Cassandra connection established
Connected to cluster: Test Cluster
Datatacenter: datacenter1; Host: /127.0.0.1; Rack: rack1
Process finished with exit code 0
然后我尝试了以下操作:
- 在 cassandra 服务器关闭的情况下运行相同的代码
- 在远程服务器上运行相同的代码
- 在没有连接的远程服务器上运行相同的代码(超时)
所有三种情况都会导致错误,但代码仍然自行退出。
cluster.shutdown();
是清理 com.datastax.driver.core.Cluster
对象使用的连接的正确方法。使用 System.exit(0) 会终止进程,但它被认为是不好的做法。此代码应该自行执行并完成。我的建议是检查您的运行(执行)设置,看看是否有任何可能与您的应用程序交互/干扰的内容。
关于java - 如何在进程完成后停止执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17123590/