我在依赖于到远程服务器的 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;
}
}
}
但是,这个解决方案不是很优雅。此外,该用例看起来非常通用,我怀疑这可以由一些有用的库来完成。唉,我找不到任何 - 谁能告诉我如何改进我的解决方案?
最佳答案
我认为这个用例足够简单,可以自己实现而不是引入额外的依赖项。如果您担心您的解决方案不够优雅,我建议将其重构为几个更小的方法,例如:
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);
}
关于java - 停止当前线程并等待 HTTP 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30211527/