gpt4 book ai didi

java - 有没有办法在 webflux 代码中等待异步方法结果

转载 作者:行者123 更新时间:2023-12-02 08:48:25 32 4
gpt4 key购买 nike

我使用Spring webflux和Intellij idea进行开发,现在遇到一个问题是,在我的方法中,我需要从reactive 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 吗?

最佳答案

您的构造是一个非常肮脏的黑客行为,不要这样做并尝试避免 react 流中的任何副作用操作。
所以,你只需要像这样链接你的操作符:

return repository.findBySymbol(symbol)
.map(xxxxx)
.map(ip -> webClient.method(httpMethod).uri(ip))
...
flatMap(param -> forwardRequest.exchange())

关于java - 有没有办法在 webflux 代码中等待异步方法结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60936249/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com