WebClient从订阅返回的值

时间:2019-07-31 20:03:14

标签: java spring-boot spring-webclient

我尝试使用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);
                    }
                });

1 个答案:

答案 0 :(得分:1)

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

如果在常规的Spring Web应用程序中使用WebClient,则可以为Block()调用WebClient以获取线程中的数据块,直到接收到数据,然后为你。

如果在WebClient应用程序中使用Webflux,则应将MonoFlux一直返回给主叫客户端,因为它是主叫客户端订户。客户端(例如React应用,Angular应用或其他应用)订阅了您的spring应用。您的spring应用程序将依次订阅其他内容,然后将数据中继到原始订阅者。

您没有说明要编写哪种类型的应用程序,并且您的代码含糊不清,这又意味着答案也很模糊。