【问题标题】:block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-nio-5block()/blockFirst()/blockLast() 是阻塞的,线程 reactor-http-nio-5 不支持
【发布时间】:2022-07-19 03:10:50
【问题描述】:

我正在使用 Spring Boot 版本“2.4.5”和“org.springframework.boot:spring-boot-starter-webflux”。当我尝试执行下面的代码时,我收到以下错误block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-nio-5 我尝试使用 toFuture() 和 share() 方法,但它们不起作用。

    String Student = webClient.get()
            .uri("MY_URL")
            .accept(MediaType.APPLICATION_JSON)
            .retrieve()
            .bodyToMono(Student.class)
            .block();
    
    boolean isValid = verifyStudentInfo(student);
    
    if (isValid) {
        method1();
    } else {
        method2();
    }

就我而言,我需要阻塞操作,因为稍后我将在代码中使用结果。我不想使用 RestTemplate,因为它将被弃用,而且我的项目中已经有 WebClient 配置,包括 ReactiveClientRegistrationRepository。

无论如何我可以启用阻塞操作吗?

【问题讨论】:

  • 这取决于,如果您正在编写一个纯 webflux 应用程序,那么阻塞对性能非常不利,并且您会得到异常,因为它是不允许的。 I need the operation to be blocking because I will be using the result later in the code能否请您更新您的代码以详细说明此语句,为什么稍后需要结果。我们需要更多的上下文来给你一个正确的答案。
  • @Toerktumlare 我更新了代码!
  • 它的上下文仍然很少,如果您希望我们这样做,请付出一些努力,这意味着我的回答会很短。使用flatMap 函数,如果您不知道这意味着什么,我建议您阅读反应器文档,因为flatMap 是反应式编程的绝对基础。
  • 重要的问题是,正如@Toerktumlare 之前问过的,“这是一个纯粹的 webflux 应用程序吗?”如果是这样,你不应该阻止。
  • @MichaelMcFadyen 这实际上不是一个纯粹的 webflux 应用程序。我需要阻塞和非阻塞。但是我不想使用 RestTemplate 进行阻塞,而是想使用 WebClient,因为我已经有了 WebClient 配置,并且将来会弃用 RestTemplate。

标签: java spring spring-boot netty spring-webflux


【解决方案1】:

响应式 API/进程不应该在客户端或浏览器订阅的发布者管道之外运行。如果您需要在您的 api 中访问发布者的数据,您可以使用 flatMap 将其集成到您的发布者管道中,并驱动您的业务逻辑,这些逻辑将在客户端订阅发布者后执行。

如果你想使用整数值来驱动你的业务逻辑,你可以使用类似的东西

    Mono<String> useValFromMono() {
        return getMono().flatMap(valFromMono -> getPublisherBasedOnVal(valFromMono)).then(Mono.defer(() -> Mono.just("then")));
    }

    Mono<Integer> getMono() {
        return Mono.fromSupplier(() -> Integer.valueOf(2));
    }

    Mono<Void> getPublisherBasedOnVal(Integer integer) {
        if(integer == 2) {
            return Mono.fromRunnable(() -> System.out.println("Its 2!"));
        }
        return Mono.empty();
    }

【讨论】:

    猜你喜欢
    • 2019-04-15
    • 2020-04-21
    • 1970-01-01
    • 2021-08-04
    • 2018-12-29
    • 1970-01-01
    • 1970-01-01
    • 2014-12-20
    • 1970-01-01
    相关资源
    最近更新 更多