【问题标题】:Spring WebFlux How to get Flux execute result?Spring WebFlux 如何获取 Flux 执行结果?
【发布时间】:2019-04-04 10:56:34
【问题描述】:

我想在 Spring WebFlux 中使用 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!

【问题讨论】:

    标签: spring-webflux spring-webclient


    【解决方案1】:

    您可以使用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));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-24
      • 2018-12-12
      • 2018-06-17
      • 2021-08-14
      • 1970-01-01
      • 2019-05-18
      • 2019-01-11
      • 1970-01-01
      相关资源
      最近更新 更多