代码之家  ›  专栏  ›  技术社区  ›  Gonen I

在为所有对象阻塞之后从列表中的Monos获取对象的值

  •  0
  • Gonen I  · 技术社区  · 5 年前

    我正在关注Rossen Stoyanchev在Spring上的演示

    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对象的值吗?如果是,怎么做?

    0 回复  |  直到 5 年前
        1
  •  2
  •   Chr3is    5 年前

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

    @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
  •  2
  •   Bartosz Kiebdaj    5 年前

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