Spring WebFlux如何获取Flux执行结果?

Spring WebFlux How to get Flux execute result?

我想用SpringWebFlux中的WebClient来调用一些url,然后把所有的monos都flux。当我调用 Flux.blockLast 时,我无法得到结果。

    @Test
    public void reactiveGetTest() {
        long start = System.currentTimeMillis();
        List<String> results = new ArrayList<>();
        List<Mono<String>> monos = IntStream.range(0, 500)
                .boxed()
                .map(i -> reactiveGet("https://www.google.com/"))
                .collect(Collectors.toList());
        Flux.mergeSequential(monos)
                .map(results::add)
                .blockLast();
        System.out.println("result: " + results.size());
        System.out.println("total time: " + (System.currentTimeMillis() - start));
    }
    private Mono<String> reactiveGet(String url) {
        return WebClient.create(url)
                .get()
                .retrieve()
                .bodyToMono(String.class);
    }

我想得到一个大小为 500 的列表,但是是 0!

您可以使用 Flux.collectList() 获取列表中的所有结果:

@Test
public void reactiveGetTest() {
    long start = System.currentTimeMillis();
    List<Mono<String>> monos = IntStream.range(0, 500)
            .boxed()
            .map(i -> reactiveGet("https://www.google.com/"))
            .collect(Collectors.toList());
    List<String> results = Flux.mergeSequential(monos).collectList().block();
    System.out.println("result: " + results.size());
    System.out.println("total time: " + (System.currentTimeMillis() - start));
}