【问题标题】:Getting values of Objects from Monos in a list after blocking for all of them在阻止所有对象后从列表中获取 Monos 对象的值
【发布时间】:2019-11-29 17:03:32
【问题描述】:

我正在关注 Rossen Stoyanchev 关于 Spring Reactive 的演示

https://www.youtube.com/watch?v=IZ2SoXUiS7M&t=935s

,并调用三个延迟的 API,然后阻塞直到它们全部完成。

List<Mono<Person>> personMonos = Stream.of(1, 2, 3)
        .map(i -> client.get().uri("/person/{id}", i).retrieve().bodyToMono(Person.class))
        .collect(Collectors.toList());

// Declare that we want to block until all monos in the list are done
Mono.when(personMonos).block();

接下来,我可以获取三个返回的 Person 对象的三个调用阻塞完成后的值吗?如果有,怎么做?

【问题讨论】:

    标签: java spring spring-webflux reactor reactive-streams


    【解决方案1】:

    单声道列表是一个助焊剂,助焊剂可以这样使用:

    @Test
    public void test() {
    
        Flux<Person> persons = Flux.just(1, 2, 3)
                .map(this::doRequest);
    
        List<Person> personList = persons.collectList().block();
    }
    
    
    @RequiredArgsConstructor
    @Getter
    static class Person {
        private final int id;
    }
    
    private Person doRequest(int id) {
        return new Person(id);
    }
    

    您可以在这里找到更多信息:https://projectreactor.io/docs/core/snapshot/reference/#core-features

    【讨论】:

      【解决方案2】:

      你可以压缩你所有的 Mono 来做一些动作,比如:

      Mono.zip(Mono.just(1), Mono.just(2), Mono.just(3)).block();
      

      【讨论】:

      • 我认为这是正确的答案。至少,这是我一直在寻找的答案 :-)
      猜你喜欢
      • 2017-09-13
      • 1970-01-01
      • 2023-02-23
      • 2019-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多