每当我使用任何 Hector API 函数访问我的 Cassandra 数据库时,都会出现异常:
me.prettyprint.hector.api.exceptions.HectorException:所有主机池标记为已关闭。重试负担推给客户端。
我的服务器确实在后台运行 Cassandra 数据库。
我阅读了异常,它实际上没有记录。似乎异常是由于连接问题。
我如何解决它?
如果 Hector 客户端无法连接到 Cassandra,您将收到该错误。这可能有很多原因和尝试的方法:
我在使用cassandra-unit 2.0.2.1时遇到了同样的错误,但是将版本降级到2.0.2.0解决了这个问题。这很奇怪,但我现在使用2.0.2.0和一些额外的 sbt依赖项
"com.datastax.cassandra" % "cassandra-driver-core" % "2.0.1",
"org.cassandraunit" % "cassandra-unit" % "2.0.2.0" withSources() withJavadoc()
由于网络连接问题,我随机收到此错误,但重试几次通常会修复它。这是我用来重试 Hector API 函数的代码:
/** An interface where inside the execute() method I call Hector */
public interface Retriable<T> {
T execute();
}
/**
* Executes operation and retries N times in case of an exception
* @param retriable
* @param maxRetries
* @param <T>
* @return
*/
public static <T> T executeWithRetry(Retriable<T> retriable, int maxRetries) {
T result;
int retries = 0;
long sleepSec = 1;
// retry in case of an exception:
while (true) {
try {
result = retriable.execute();
break;
} catch (Exception e) {
if (retries == maxRetries) {
LOG.error("Exception occurred. Reached max retries.", e);
throw e;
}
retries++;
LOG.error(String.format("Exception occurred. Retrying in %d seconds - #%d", sleepSec, retries), e);
try {
Thread.sleep(sleepSec * 1000);
// increase sleepSec exponentially:
sleepSec *= 2;
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
return result;
}
以及如何使用它的示例:
ColumnFamilyResult<String, String> columns = executeWithRetry(new Retriable<ColumnFamilyResult<String, String>>() {
@Override
public ColumnFamilyResult<String, String> execute() {
return template.queryColumns(row.getKey());
}
});