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

时间:2019-04-04 10:56:34

标签: spring-webflux spring-webclient

我想在Spring WebFlux中使用WebClient来调用一些url,然后将所有monos转换为助焊剂。当我调用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!

1 个答案:

答案 0 :(得分: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));
}