我正在编写一些重新连接逻辑,以定期尝试建立与已关闭的远程端点的连接。本质上,代码如下所示:
public void establishConnection() {
try {
this.connection = newConnection();
} catch (IOException e) {
// connection failed, try again.
try { Thread.sleep(1000); } catch (InterruptedException e) {};
establishConnection();
}
}
我已经多次使用与上述类似的代码解决了这个普遍问题,但我对结果很不满意。是否有专门用于处理此问题的设计模式?
最佳答案
无耻插件:我已经实现了一些允许重试操作的类。 该库尚未提供,但您可以fork it on github 。
还有一个 fork存在。
它允许构建具有各种灵活策略的重试器。例如:
Retryer retryer =
RetryerBuilder.newBuilder()
.withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECOND))
.withStopStrategy(StopStrategies.stopAfterAttempt(3))
.retryIfExceptionOfType(IOException.class)
.build();
然后您可以使用重试器执行一个可调用的(或多个):
retryer.call(new Callable<Void>() {
public Void call() throws IOException {
connection = newConnection();
return null;
}
}
关于java - 失败的 "retrying"逻辑的设计模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11692595/