apache fluent httpclient的重试策略

  |   0 评论   |   0 浏览

背景

apache fluent httpclient的api非常好用,但是直接使用,失败后,是不会进行重试的。

初体验

apache的fluent httpclient是支持重试策略的,只是默认没有打开。

给一个使用重试的示例:

import java.io.IOException;

import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.fluent.Executor;
import org.apache.http.client.fluent.Request;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HttpContext;

public class RetrySample {
	public static void main(String[] args) {
		try {
			// allow retry
			HttpRequestRetryHandler retryHandler = (IOException exception, int executionCount, HttpContext context) -> {
				return executionCount <= 3;
			};

			HttpClient httpClient = HttpClientBuilder.create().setRetryHandler(retryHandler).build();
			Executor fluentExecutor = Executor.newInstance(httpClient);
			String str = fluentExecutor
					.execute(Request.Get("http://noexist.abeffect.com").connectTimeout(10000).socketTimeout(10000))
					.returnContent().asString();
			System.out.println(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

参考