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



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

你的构建是一个非常肮脏的黑客,不要这样做并尽量避免反应流中的任何副作用操作
所以,你只需要像这样连锁你的运营商:

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

最新更新