【问题标题】:WebClient return value from subscribeWebClient 从订阅返回值
【发布时间】:2019-12-09 09:45:23
【问题描述】:

我尝试使用 webclient 非阻塞方法来验证验证码响应。所以 它可以工作,但我需要我的方法返回布尔值而不是异常。我如何从订阅中返回值?

        webClient
                .post()
                .uri(verifyUri)
                .exchange()
                .flatMap(res -> res.bodyToMono(GoogleResponse.class))
                .doOnError(e -> log.error("Request error"))
                .subscribe(GoogleResponse -> {
                    try {
                        log.debug("Google response: {}", GoogleResponse);
                        if (!GoogleResponse.isSuccess()) {
                            throw new ReCaptchaInvalidException("reCaptcha response is not valid");
                        }
                    } catch (ReCaptchaInvalidException e) {
                        throw new ReCaptchaUnavailableException("Registration unavailable at this time.  Please try again later.", e);
                    }
                });

【问题讨论】:

    标签: java spring-boot spring-webclient


    【解决方案1】:

    首先,您是在编写 Webflux 应用程序还是只是在 Spring Web 应用程序中使用 WebClient 而不是 RestTemplate。

    如果在常规 Spring Web 应用程序中使用 WebClient,您只需为 WebClient 调用 Block() 以获取数据块线程,直到接收到数据,然后为您返回数据。

    如果在Webflux 应用程序中使用WebClient,您应该将Mono 或Flux 一直返回给调用客户端,因为调用客户端是订阅者。客户端(比如 React 应用程序、Angular 应用程序或其他)订阅您的 Spring 应用程序。您的 Spring 应用程序反过来订阅其他内容,然后将数据转发给原始订阅者。

    您没有说明您正在编写什么样的应用程序,并且您的代码有点模糊,这反过来意味着答案也很模糊。

    【讨论】:

    • 我必须在我的 springboot 应用程序中使用 WebClient,因为 resttemplate 很快就会被弃用
    • 实际上,“常规 Spring Web 应用程序”也支持响应式返回类型,请参见此处:docs.spring.io/spring/docs/current/spring-framework-reference/…(表中倒数第二行)。
    • 我没有提到它不支持响应式返回类型的任何地方。我写了你可以......你应该......
    猜你喜欢
    • 1970-01-01
    • 2018-07-30
    • 2018-09-04
    • 2017-07-14
    • 1970-01-01
    • 1970-01-01
    • 2019-11-12
    • 1970-01-01
    • 2021-07-16
    相关资源
    最近更新 更多