停止当前线程并等待 HTTP 连接

Stop current thread & wait for HTTP connection

我 运行 线程中的某些逻辑依赖于与远程服务器的 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;
                        }
                    }
                }

但是,这个方案不是很优雅。此外,该用例看起来非常通用,我怀疑这可以由一些有用的库来完成。唉,我找不到任何 - 谁能告诉我如何改进我的解决方案?

Camel 为这些用例提供支持:http://camel.apache.org/http

然而,它更像是一个构建 data-stream/event-driven 应用程序的框架,因此重试与 http 服务器的连接可能是一个非常大的锤子。但是,如果它适合应用程序,那么移动数据是一个很好的 library/framework。

我认为这个用例足够简单,可以自己实现而不是引入额外的依赖项。如果您担心您的解决方案不够优雅,我建议将其重构为几个更小的方法,例如:

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);
}