【问题标题】:Best way to implement parallel processing of async services in Spring在 Spring 中实现异步服务并行处理的最佳方法
【发布时间】:2017-10-04 10:30:32
【问题描述】:

如果你愿意,我需要一些建议。我需要从我的 spring 应用程序中并行调用几个异步服务。我的意思是:代码应该和最慢的异步任务一样慢

我已经按照以下方式对其进行了编码,但我不太确定这是否是最好的方式。可能不是xD。事实上,我不太习惯 java8 lambdas 和流的东西,所以我可以成为改进点。

```

 @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();

能否请您指出正确的方向?

提前非常感谢!

【问题讨论】:

    标签: spring asynchronous spring-boot


    【解决方案1】:

    您可能想使用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();
    
    • 您需要先从 Service 中删除所有 @Async。
    • 无需使用 AsyncResult 包装 MyResult

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-01
    • 1970-01-01
    • 2010-12-04
    • 2019-08-04
    • 2020-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多