Java中处理并行API调用的正确方法
我有一个Java的web应用程序,作为客户端HTTP请求处理的一部分,我需要进行2个API调用。我计划实现的方法是将一个API调用卸载到线程池,在同一个线程中执行另一个调用,然后合并结果。 我想并行处理API1调用,但不想在队列中阻止它。因此,如果没有可用的线程,我将按顺序执行。 这就是我想到的Java中处理并行API调用的正确方法,java,multithreading,future,executor,Java,Multithreading,Future,Executor,我有一个Java的web应用程序,作为客户端HTTP请求处理的一部分,我需要进行2个API调用。我计划实现的方法是将一个API调用卸载到线程池,在同一个线程中执行另一个调用,然后合并结果。 我想并行处理API1调用,但不想在队列中阻止它。因此,如果没有可用的线程,我将按顺序执行。 这就是我想到的 //this is already created in setup, just listing here for reference. ThreadPoolExecutor tpe = new Thr
//this is already created in setup, just listing here for reference.
ThreadPoolExecutor tpe = new ThreadPoolExecutor(1, 2, 300, TimeUnit.SECONDS, new SynchronousQueue<>());
.....
private Future<Integer> getDataFromAPI1(ThreadPoolExecutor tpe){
try {
return tpe.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
//....make API call here
return 1; //return result
}
});
}catch (RejectedExecutionException r){
//do sequentially and throw any exception encountered
///.....
return CompletableFuture.completedFuture(1); //return the result
}
}
public Integer handle(String reqStub){
Future<Integer> f1 = getDataFromAPI1(tpe);
//make API call2 here in same thread
//... this populates r2
Integer r1 = f1.get();
//now return final result based on 2 results
return r1+r2;
}
//这已在安装程序中创建,仅在此处列出以供参考。
ThreadPoolExecutor tpe=新的ThreadPoolExecutor(1,2300,TimeUnit.SECONDS,new SynchronousQueue());
.....
私有未来getDataFromAPI1(ThreadPoolExecutor tpe){
试一试{
返回tpe.submit(新的可调用(){
@凌驾
公共整数调用()引发异常{
//…在此处进行API调用
返回1;//返回结果
}
});
}捕获(拒绝执行异常r){
//按顺序执行并抛出遇到的任何异常
///.....
return CompletableFuture.completedFuture(1);//返回结果
}
}
公共整数句柄(字符串){
未来f1=从API1获取数据(tpe);
//在同一线程中进行API调用2
//…这将填充r2
整数r1=f1.get();
//现在根据2个结果返回最终结果
返回r1+r2;
}
假设异常处理由handle()方法的调用方完成。
代码片段的正确性和性能是否良好。
是否有更好的方法实现同样的目标?“按顺序执行并抛出遇到的任何异常”是错误的。而不是抛出异常,它应该返回<代码>新的完整的FutUTE()。