CloseableHttpClient:如果有的话,所有异常都会转到retyHandler()吗?

问题描述 投票:1回答:1

所以我按照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()?

java apache-httpclient-4.x closeablehttpresponse
1个回答
1
投票
  1. 异常逻辑由请求执行管道内的HttpClient实现。 HttpRequestRetryHandler仅仅是一个决策策略,用于确定是否会重新执行失败的请求。我承认HttpRequestRetryHandler可能是用词不当。它实际上不是一个处理程序。
  2. 只有I / O异常被认为是可恢复的。运行时异常传播给调用者。
© www.soinside.com 2019 - 2024. All rights reserved.