小编Den*_*sen的帖子

如何在Spring Webflux/Reactor Netty Web应用程序中执行阻塞调用

在我的用例中,我有一个带有Reactor Netty的Spring Webflux微服务,我有以下依赖项:

  • org.springframework.boot.spring-boot-starter-webflux (2.0.1.RELEASE)
  • org.springframework.boot.spring-boot-starter-data-mongodb-reactive (2.0.1.RELEASE)
  • org.projectreactor.reactor-spring (1.0.1.RELEASE)

对于一个非常具体的案例,我需要从Mongo数据库中检索一些信息,并将其处理成与我的被动发送的查询参数WebClient.由于WebClient并且UriComponentsBuilder接受发布者(Mono/Flux)我使用了一个#block()调用来接收结果.

由于reactor-core(版本0.7.6.RELEASE)已包含在最新spring-boot-dependencies版本(版本2.0.1.RELEASE)中,因此无法再使用:block()/blockFirst()/blockLast() are blocking, which is not supported in thread xxx,请参阅 - > https://github.com/reactor/reactor-netty/问题/ 312

我的代码片段:

public Mono<FooBar> getFooBar(Foo foo) {
    MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
    parameters.add("size", foo.getSize());
    parameters.addAll("bars", barReactiveCrudRepository.findAllByIdentifierIn(foo.getBarIdentifiers()) // This obviously returns a Flux
        .map(Bar::toString)
        .collectList()
        .block());

    String url = UriComponentsBuilder.fromHttpUrl("https://base-url/")
        .port(8081)
        .path("/foo-bar")
        .queryParams(parameters)
        .build()
        .toString();

    return webClient.get()
        .uri(url)
        .retrieve()
        .bodyToMono(FooBar.class);
}
Run Code Online (Sandbox Code Playgroud)

这适用于spring-boot …

spring-data-mongodb project-reactor reactor-netty spring-webflux

6
推荐指数
1
解决办法
8758
查看次数

Spring WebFlux webclient 处理 ConnectTimeoutException

我正在使用 Spring WebFlux webclient 进行 REST 调用。我已经以3000毫秒为单位配置了连接超时,因此:

WebClient webClient = WebClient.builder()
    .clientConnector(new ReactorClientHttpConnector(options -> options
        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)))
    .build();

return webClient.get()
    .uri("http://localhost:8081/resource")
    .retrieve()
    .onStatus(HttpStatus::isError, clientResponse -> {
        // Some logging..
        return Mono.empty();
    })
    .bodyToMono(MyPojo.class);
Run Code Online (Sandbox Code Playgroud)

onStatus方法Mono为每个400/500响应代码返回一个空值。我怎样才能对连接超时甚至读/写超时做同样的事情。现在它只是抛出一个io.netty.channel.ConnectTimeoutException不被处理的onStatus

我的@ExceptionHandler控制器上不需要,因为这些 REST 调用是更复杂流程的一部分,并且通过空Mono元素应该被忽略。

回来spring-web用一个RestTemplate,我记得连接超时也导致了一个RestClientException。所以我们可以捕获RestClientException所有异常和超时。有没有办法我们也可以做到这一点WebClient

reactor-netty spring-webflux

5
推荐指数
1
解决办法
2723
查看次数