我在一个Thread中运行一些逻辑,它依赖于与远程服务器的HTTP连接。目前,如果远程服务器未运行,则线程崩溃。我想修改逻辑,以便线程等待远程服务器再次可用。
从技术上讲,解决方案似乎是向前发展的。有点像:
boolean reconnect = false;
while (!reconnect) {
try {
URL url = new URL("my.remoteserver.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
reconnect = true;
} catch (Exception ex) {
// wait a little, since remote server seems still down
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
// if thread was interrupted while waiting then terminate thread
break;
}
}
}
然而,这个解决方案不是很优雅。此外,用例似乎非常通用,我怀疑这可以通过一些有用的库来完成。唉,我找不到 - 谁能告诉我如何改进我的解决方案?
答案 0 :(得分:1)
我认为这个用例很简单,可以自己实现,而不是引入额外的依赖项。如果您担心您的解决方案不是很优雅,我建议将其重构为几个较小的方法,例如:
public void connect() {
try {
connectWithRetries();
} catch (InterruptedException e) {
// Continue execution
}
}
private void connectWithRetries() throws InterruptedException {
while (!tryConnect()) {
sleep();
}
}
private boolean tryConnect() {
try {
URL url = new URL("my.remoteserver.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
} catch (Exception e) {
return false;
}
return true;
}
private void sleep() throws InterruptedException {
Thread.sleep(5000);
}
答案 1 :(得分:0)
Camel为这类用例提供支持:http://camel.apache.org/http
然而,它更像是一个构建数据流/事件驱动的应用程序的框架,因此重试与http服务器的连接可能是一个非常大的麻烦。但是,如果它适合应用程序,它是一个很好的库/框架来移动数据。