Bri*_*ger 1 spring asynchronous spring-boot
如果你愿意的话,我需要一些建议。我需要从我的 Spring 应用程序并行调用几个异步服务。我的意思是:代码应该和最慢的异步任务一样慢
我用以下方式对其进行了编码,但我不太确定这是否是最好的方式。可能不是xD。事实上,我不太习惯 java8 lambda 和流的东西,所以我可以是一个改进点。
````
@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));
}
}
Run Code Online (Sandbox Code Playgroud)
然后,在另一个春季服务中,我有以下内容:
````
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();
Run Code Online (Sandbox Code Playgroud)
如果可以的话,您能给我指出正确的方向吗?
预先非常感谢!
您可能想使用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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6318 次 |
| 最近记录: |