如果您愿意,我需要一些建议。我需要从我的spring应用程序中并行调用几个异步服务。我的意思是:代码应该与最慢的异步任务一样慢
我已经按照以下方式对其进行了编码,但我不太确定这是否是最好的方法。可能不是xD。事实上,我并不习惯java8 lambdas和stream的东西,所以我可能会有所改进。
```
@Service
@Qualifier("service1")
public class Service1 implements IService {
@Async("processExecutor")
public AsyncResult<MyResult> doStuff(Stuff input){
return new AsyncResult<Optional<MyResult>>(callStuff(input));
}
}
@Service
@Qualifier("service2")
public class Service2 implements IService {
@Async("processExecutor")
public AsyncResult<MyResult> doStuff(Stuff input){
return new AsyncResult<Optional<MyResult>>(callStuff(input));
}
}
@Service
@Qualifier("service3")
public class Service3 implements IService {
@Async("processExecutor")
public AsyncResult<MyResult> doStuff(Stuff input){
return new AsyncResult<Optional<MyResult>>(callStuff(input));
}
}
然后,在另一个春季服务中,我有以下内容:
```
AsyncResult<MyResult>aResult1=service1.doStuff(input);
AsyncResult<MyResult>aResult2=service2.doStuff(input);
AsyncResult<MyResult>aResult3=service3.doStuff(input);
MyResult result1= aResult1.get();
MyResult result2= aResult2.get();
MyResult result2= aResult3.get();
如果你愿意,你会指出我正确的方向吗?
提前多多感谢!
答案 0 :(得分:2)
您可能想要使用CompletableFuture.allOf
CompletableFuture<MyResult> futur1=CompletableFuture.supplyAsync( ()->{return service1.doStuff(input);});
CompletableFuture<MyResult> futur2=CompletableFuture.supplyAsync( ()->{return service2.doStuff(input);});
CompletableFuture<MyResult> futur3=CompletableFuture.supplyAsync( ()->{return service3.doStuff(input);});
CompletableFuture<Void> allCompleted = CompletableFuture.allOf(futur1,futur2,futur3);
allCompleted.get();// this one will block current thread until futur1,futur2,futur3 done.
MyResult r1 = futur1.get();
MyResult r2 = futur2.get();
MyResult r3 = futur3.get();