【问题标题】:Calling multiple services concurrently inside a method在一个方法中同时调用多个服务
【发布时间】:2020-03-24 05:23:42
【问题描述】:

我有一个场景,我应该在一个方法中同时调用 4 个不同的外部服务,如果线程中的任何一个将首先获取数据,那么我需要取消线程的其余部分并返回响应。

class ProductService{
    public List<Product> getProducts(){
       // logic to call multiple services concurrently 
       // if any of the thread get the data then cancel the rest concurrent call gracefully
       // return the response
    }
}

谁能帮我实现这个逻辑。

【问题讨论】:

  • 您想无限期地阻止,直到收到第一个响应,对吧?

标签: java multithreading spring-boot concurrency parallel-processing


【解决方案1】:

客户

public Mono<Product> getProduct(String productId) {
  // api request using spring webclient
}

消费者

Mono<Product> request1 = getProduct("1");
Mono<Product> request2 = getProduct("2");

Product product = Flux.merge(request1, request2).blockFirst();

这将无限期地阻塞,直到其中一个请求返回。 这使用 Spring webflux。更多关于这个here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多