0

在我基于 Java-Spring 的 Web 应用程序中,我使用Hector 和 Spring连接到Cassandra DB 。

连接工作得很好,但我希望能够测试连接。

因此,如果我故意向 CassandraHostConfigurator 提供错误的主机,则会收到错误消息:

ERROR connection.HConnectionManager: Could not start connection pool for host <myhost:myport>

这当然可以。但是我怎样才能测试这个连接呢?

如果我务实地定义连接(而不是通过弹簧上下文),那很清楚,但是通过弹簧上下文,如何测试它并不清楚。

你能想出一个主意吗?

4

1 回答 1

0

由于我找不到满意的答案,我决定务实地定义我的连接并使用一个简单的查询:

private ColumnFamilyResult<String, String> readFromDb(Keyspace keyspace) {
ColumnFamilyTemplate<String, String> template = new ThriftColumnFamilyTemplate<String, String>(keyspace, tableName, StringSerializer.get(),
    StringSerializer.get());
// It doesn't matter if the column actually exists or not since we only check the
// connection. In case of connection failure an exception is thrown,
// else something comes back.
return template.queryColumns("some_column");
}

我的测试检查返回的对象是否不为空。

另一种工作正常的方法:

public boolean isConnected() {
List<KeyspaceDefinition> keyspaces = null;
try {
    keyspaces = cluster.describeKeyspaces();
} catch (HectorException e) {
    return false;
}
return (!CollectionUtils.isEmpty(keyspaces));
}
于 2013-07-30T14:03:10.570 回答