cassandra单节点连接错误

时间:2015-01-15 21:14:15

标签: java cassandra datastax-java-driver

我正在尝试使用cassandra作为我正在处理的应用程序的数据库。该应用程序是一个Netbeans平台应用程序。 为了在我的localhost上启动cassandra服务器,我发出Runtime.getRuntime()。exec(command) 其中command是启动cassandra服务器的字符串,然后我使用datastax驱动程序连接到cassandra服务器。但是我得到错误:

com.datastax.driver.core.exceptions.NoHostAvailableException: All host(s) tried for query   failed (tried: /127.0.0.1:9042 (com.datastax.driver.core.TransportException: [/127.0.0.1:9042]  Cannot connect))
at com.datastax.driver.core.ControlConnection.reconnectInternal(ControlConnection.java:199)
at com.datastax.driver.core.ControlConnection.connect(ControlConnection.java:80)
at com.datastax.driver.core.Cluster$Manager.init(Cluster.java:1154)
at com.datastax.driver.core.Cluster.getMetadata(Cluster.java:318)
at org.dhviz.boot.DatabaseClient.connect(DatabaseClient.java:43)
at org.dhviz.boot.Installer.restored(Installer.java:67)
....

我发现服务器需要一些时间来启动,所以我添加了Thread.sleep(MAX_DELAY_SERVER)行似乎可以解决问题。

有没有更优雅的方法来解决这个问题? 感谢。

代码如下。

public class Installer extends ModuleInstall {

private final int MAX_DELAY_SERVER = 12000;

//private static final String pathSrc = "/org/dhviz/resources";
@Override
public void restored() {

    /*
     -*-*-*-*-*DESCRIPTION*-*-*-*-*-*
     IMPLEMENT THE CASSANDRA DATABASE
     *********************************
     */
    DatabaseClient d = new DatabaseClient();
    // launch an instance of the cassandra server 
    d.loadDatabaseServer();


    /*wait for MAX_DELAY_SERVER milliseconds before launching the other instructions. 
    */
    try {
        Thread.sleep(MAX_DELAY_SERVER);
        Logger.getLogger(Installer.class.getName()).log(Level.INFO, "wait for MAX_DELAY_SERVER milliseconds before the connect database");
    } catch (InterruptedException ex) {
        Exceptions.printStackTrace(ex);
        Logger.getLogger(Installer.class.getName()).log(Level.INFO, "exeption in thread sleep");
    }

    d.connect("127.0.0.1");

}
}



public class DatabaseClient {

private Cluster cluster;
private Session session;
private ShellCommand shellCommand;
private final String defaultKeyspace = "dhviz";

final private String LOAD_CASSANDRA = "launchctl load    /usr/local/Cellar/cassandra/2.1.2/homebrew.mxcl.cassandra.plist";

final private String UNLOAD_CASSANDRA = "launchctl unload /usr/local/Cellar/cassandra/2.1.2/homebrew.mxcl.cassandra.plist";

public DatabaseClient() {
    shellCommand = new ShellCommand();

}

public void connect(String node) {
//this connect to the cassandra database

    cluster = Cluster.builder()
            .addContactPoint(node).build();
//  cluster.getConfiguration().getSocketOptions().setConnectTimeoutMillis(12000);
    Metadata metadata = cluster.getMetadata();
    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());

    }

        session = cluster.connect();


    Logger.getLogger(DatabaseClient.class.getName()).log(Level.INFO, "connected to server");
}

public void loadDatabaseServer() {
    if (shellCommand == null) {

        shellCommand = new ShellCommand();

    }
    shellCommand.executeCommand(LOAD_CASSANDRA);
    Logger.getLogger(DatabaseClient.class.getName()).log(Level.INFO, "database cassandra loaded");
}

public void unloadDatabaseServer() {
    if (shellCommand == null) {

        shellCommand = new ShellCommand();

    }

    shellCommand.executeCommand(UNLOAD_CASSANDRA);

    Logger.getLogger(DatabaseClient.class.getName()).log(Level.INFO, "database cassandra unloaded");
}

}

2 个答案:

答案 0 :(得分:1)

如果您在Runtime.getRuntime().exec(command)中调用没有任何参数的cassandra,则可能会将cassandra作为后台进程生成并在cassandra节点完全启动并正在侦听之前返回。

我不确定您为什么试图在您的应用中嵌入cassandra,但您可能会发现使用cassandra-unit非常有用,可以在您的应用中提供嵌入cassandra的机制。它主要用于运行需要cassandra实例的测试,但它也可以满足您的使用案例。

The wiki提供了有关如何使用cassandra-unit启动嵌入式cassandra实例的有用示例:

EmbeddedCassandraServerHelper.startEmbeddedCassandra();

根据我的经验,cassandra-unit将等到服务器启动并在返回之前监听。您还可以使用与this answer相反的逻辑编写一个等待套接字正在使用的方法。

答案 1 :(得分:0)

我已将代码更改为以下内容从以下答案中获取灵感。谢谢你的帮助!

cluster = Cluster.builder()
            .addContactPoint(node).build();

    cluster.getConfiguration().getSocketOptions().setConnectTimeoutMillis(50000);

    boolean serverConnected = false;
    while (serverConnected == false) {
        try {
            try {
                Thread.sleep(MAX_DELAY_SERVER);

            } catch (InterruptedException ex) {
                Exceptions.printStackTrace(ex);
            }
            cluster = Cluster.builder()
                    .addContactPoint(node).build();

            cluster.getConfiguration().getSocketOptions().setConnectTimeoutMillis(50000);
            session = cluster.connect();
            serverConnected = true;

        } catch (NoHostAvailableException ex) {
            Logger.getLogger(DatabaseClient.class.getName()).log(Level.INFO, "trying connection to cassandra server...");
            serverConnected = false;
        }

    }