java - CloseableHttpClient : will all exceptions go to retyHandler() if there's one?

标签 java apache-httpclient-4.x closeablehttpresponse

所以我正在遵循这个 retryHandler() 示例,它有 try/finally。我的问题是:如何重试异常?

public class HttpClientRetryHandlerExample {

    public static void main(String... args) throws IOException {

        CloseableHttpClient httpclient = HttpClients.custom()
                .setRetryHandler(retryHandler())
                .build();

        try {
            HttpGet httpget = new HttpGet("http://localhost:1234");
            System.out.println("Executing request " + httpget.getRequestLine());
            httpclient.execute(httpget);
            System.out.println("----------------------------------------");
            System.out.println("Request finished");
        } finally {
            httpclient.close();
        }
    }

    private static HttpRequestRetryHandler retryHandler(){
        return (exception, executionCount, context) -> {

            System.out.println("try request: " + executionCount);

            if (executionCount >= 5) {
                // Do not retry if over max retry count
                return false;
            }
            if (exception instanceof InterruptedIOException) {
                // Timeout
                return false;
            }
            if (exception instanceof UnknownHostException) {
                // Unknown host
                return false;
            }
            if (exception instanceof SSLException) {
                // SSL handshake exception
                return false;
            }
            HttpClientContext clientContext = HttpClientContext.adapt(context);
            HttpRequest request = clientContext.getRequest();
            boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
            if (idempotent) {
                // Retry if the request is considered idempotent
                return true;
            }
            return false;
        };
    }
}

问题是,为什么这个例子只有 try/finally 而没有 catch ?这是否意味着所有异常都会转到 retryHandler() ?

最佳答案

  1. 异常逻辑由请求执行管道内的 HttpClient 实现。 HttpRequestRetryHandler 只是一个决策策略,用于确定是否重新执行失败的请求。我承认 HttpRequestRetryHandler 可能用词不当。它实际上并不是一个处理程序。

  2. 只有 I/O 异常才被视为可恢复。运行时异常会传播给调用者。

关于java - CloseableHttpClient : will all exceptions go to retyHandler() if there's one?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55541476/

相关文章:

java - Eclipse Mars Glassfish 4.1 - 键值不得为空

Java-分割字符串后添加空格

Java:设置 pom.xml 属性

java - 为什么在 PoolingClientConnectionManager 中弃用所有方法?

java - 在没有锁定的情况下从多个线程写入同一个文件,Java

java - 统计对 apache HttpClient 的调用

java - 将 CloseableHttpResponse 移动到带有资源的嵌套尝试中

java - 在 java 中使用属性文件 *AS* static final 变量中的属性