有一种方法可以等待webflux代码中的异步方法结果

问题描述 投票:0回答:1

我使用Spring webflux以Intellij的思想进行开发,现在我遇到的一个问题是,在我的方法中,我需要从反应式mongo获取ip(String),然后再转发请求。所以我写了这段代码

@Autowird
private XXRepository repository;

public Mono<Void> xxxx(ServerWebExchange exchange, String symbol) {
    StringBuilder builder = new StringBuilder();
    String ip = repository.findBySymbol(symbol)
                          .map(xxxxx)
                          .subscribe(builder::append)
                          .toString();
    WebClient.RequestBodySpec forwardRequestInfo = webClient.method(httpMethod)
                .uri(ip);

    xxxxxxx //setting http msg
    WebClient.RequestHeadersSpec<?> forwardRequest;
    return forwardRequest.exchange();
}

我的问题是该代码将在其他线程上执行,我无法在我的方法中获得此ip,因为我的方法不会等待此mongo执行

String ip = repository.findBySymbol(symbol)
                          .map(xxxxx)
                          .subscribe(builder::append)
                          .toString();

所以我可以通过我的方法立即获得ip吗?

java spring-webflux reactor
1个回答
1
投票

您的构造是一个非常肮脏的技巧,不要这样做,并尝试避免在反应流中进行任何副作用操作。因此,您只需要像这样链接您的运营商:

return repository.findBySymbol(symbol)
                      .map(xxxxx)
                      .map(ip -> webClient.method(httpMethod).uri(ip))
                      ...
                      flatMap(param -> forwardRequest.exchange())
© www.soinside.com 2019 - 2024. All rights reserved.