【发布时间】:2017-08-05 19:05:01
【问题描述】:
我需要为通过 ExecutorCompletionService 调用 API 配置重试策略。
示例代码:
public void func() throws Exception{
ExecutorService executorService = Executors.newFixedThreadPool(5);
CompletionService<String> completionService = new ExecutorCompletionService<String>(executorService);
List<Future<String>> list = new ArrayList<Future<String>>();
for(int i=0; i<10; i++) {
AsyncTest asyncTest = new AsyncTest();
Future<String> futureString = completionService.submit(asyncTest);
list.add(futureString);
}
while (list.size() > 0) {
Future<String> futureResponse = completionService.take();
System.out.println(futureResponse.get());
list.remove(futureResponse);
}
executorService.shutdown();
}
public class AsyncTest implements Callable<String> {
public String call() throws Exception {
//returns a response from api call
//this is a network call and throws TimeoutException
}
}
对调用 API 时抛出的 TimeoutException 实施重试策略的最佳方法是什么?
【问题讨论】:
-
在我尝试回答之前稍微澄清一下,以确保我知道到底发生了什么。 TimeoutException 来自网络调用滞后,而不是等待执行者完成其业务?
-
是的,TimeoutException 来自网络调用滞后。
-
我认为你可以从这里得到你需要的东西stackoverflow.com/a/4738630/3630719
标签: java asynchronous executorservice retrypolicy completion-service