java—同时进行webclient调用,只完成第一次调用

vlju58qv  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(374)

我是webflux的新手,我想做以下事情:我想用不同的参数值对同一个url发出并行http请求,并在得到第一个非null(非异常)结果时停止。下面我就来举个例子https://www.baeldung.com/spring-webclient-simultaneous-calls 但当我得到结果时,我不知道如何停止。有人能帮我吗?目前我有这样的想法:

RetrySpec retrySpec = Retry.max(3);

        return webClient.get().uri("/getMyObject/{id}", id)
                .retrieve()
                .bodyToMono(MyObject.class)
                .retryWhen(retrySpec);
    }

    public Flux<> getMyObjs(List<String> ids) {
        return Flux.fromIterable(ids)
                .parallel(Runtime.getRuntime().availableProcessors())
                .runOn()
                .flatMap(this::getMyObject)
                .;//// Stop when I get first non exceptional value
    }
i86rm4rw

i86rm4rw1#

在flux中尝试next()操作符。

public Mono<MyObject> getMyObjs(List<String> ids) {
        return Flux.fromIterable(ids)
                .parallel(Runtime.getRuntime().availableProcessors())
                .runOn()
                .flatMap(this::getMyObject)
                .next();// Emit only the first item emitted by this Flux, into a new Mono. If called on an empty Flux, emits an empty Mono.
}

参考文献:https://projectreactor.io/docs/core/release/api/reactor/core/publisher/flux.html#next--
但是,也要检查firstwithsignal和firstwithvalue操作符。https://projectreactor.io/docs/core/release/api/reactor/core/publisher/flux.html#firstwithsignal-java.lang.iterable语言-https://projectreactor.io/docs/core/release/api/reactor/core/publisher/flux.html#firstwithvalue-java.lang.iterable语言-
当我遇到这样的问题时,通常我会检查文档,从fluxapi中找到合适的操作符。

相关问题