如何记录单声道通话结果?

问题描述 投票:0回答:2

我正在尝试创建一个调用多个 API 的控制器:

FIRST CALL

IF SUCCESS
    CALL ANOTHER FIRST API
    CALL ANOTHER SECOND API
ELSE
    RETURN API ERROR

为此,我使用 spring-cloud-gateway。我没有找到任何功能可以用 spring cloud 做到这一点,所以我通过 spring 控制器实现了这一点。

所以我创建了一个类,其中包含调用我的第一个 API 的方法:

public Mono<ProUserResponse> createProUser(UserCreationRequest request) {
            Function<UriBuilder, URI> uri = uriBuilder -> uriBuilder
                    .path(userProperties.getCreateProUser().privateEndpoint())
                    .build();
            HttpClient httpClient = HttpClient.create();
                httpClient.wiretap("reactor.netty.http.client.HttpClient", LogLevel.DEBUG, 
            ClientHttpConnector clientHttpConnector = new ReactorClientHttpConnector(httpClient);
    
    
            return WebClient.builder().clientConnector(clientHttpConnector).baseUrl(userProperties.getCreateProUser().baseUrl().toString()).build().post()
                            .uri(uri)
                            .accept(MediaType.APPLICATION_JSON)
                            .contentType(MediaType.APPLICATION_JSON)
                            .bodyValue(request)
                            .retrieve()
                            .bodyToMono(ProUserResponse.class)
                            .retry(3);
        }

我还创建了一个控制器:

public Mono<ResponseEntity<MerchantCreationResponse>> createNewMerchant(@Valid @RequestBody MerchantCreationRequest merchantCreationRequest) throws MerchantCreationException, ExecutionException, InterruptedException {
    // Create User
    Mono<ProUserResponse> user = monolitheHttpClient.createProUser(merchantCreationRequest.merchant()).log(log.getName());

    final AtomicReference<MerchantCreationResponse> response = null;
    //Long userId = user.toFuture().get().rakutenUserid();
    user.doOnSuccess(proUserResponse -> {
        log.info("youpi");
        System.out.println("This is a message");
    }).doOnError(throwable -> log.error("Failed for some reason", throwable));

     return Mono.just(new ResponseEntity(response, HttpStatus.OK));
}

当我调用我的控制器时,请求返回一个 Http 200 代码,但我没有登录成功或错误。

如何显示我的查询结果?这是好方法吗?

感谢您的帮助!

java spring spring-boot spring-webflux project-reactor
2个回答
0
投票

您的代码不执行那个单声道,即没有订阅它。 你的

user
单声道保持不变。

你只是创建一个可以被调用的对象,永远不会调用它,然后总是返回 200 响应,没有考虑任何实际工作。

代码应该是这样的:

return user.map(result -> {
    new ResponseEntity(result, HttpStatus.OK)
});

这意味着订阅用户单声道然后提供以下结果.


0
投票

您需要用户 Mono 的订阅者并使用 map 添加操作链以获得成功响应,并且在错误时您可以使用 onErrorResume 返回

ResponseEntity
和适当的状态代码

return user.map(data -> {
          //log the data if needed
          return new ResponseEntity(data, HttpStatus.OK)
          }).onErrorResume(throwable -> {
                 log.error("Failed for some reason", throwable));
                 return new ResponseEntity(null, HttpStatus.INTERNAL_SERVER_ERROR);
               });
© www.soinside.com 2019 - 2024. All rights reserved.