Spring Webflux webclient 问题,尝试发送 post 请求时没有任何反应

Issue with Spring Webflux webclient , nothing happens when trying to send post request

具有以下 webclient 实现:

    public <T> WebClient.ResponseSpec sendRequest(HttpMethod method, String contentType, T body, String baseUrl, String path) {
    try {
        WebClient webClient = WebClient.builder().baseUrl(baseUrl).filter(logRequest()).build();
        WebClient.ResponseSpec responseSpec = webClient.method(method)
                .uri(path)
                .header(HttpHeaders.CONTENT_TYPE, contentType)
                .body(BodyInserters.fromObject(body))
                .retrieve();
        return responseSpec;
    } catch (Exception e) {
        throw new WebClientProcessingException("Exception when trying to execute request", e);

    }
}

// This method returns filter function which will log request data
private static ExchangeFilterFunction logRequest() {
    return ExchangeFilterFunction.ofRequestProcessor(clientRequest -> {
        LOGGER.info("Request: {} {} {}", clientRequest.method(), clientRequest.url(), clientRequest.body());
        clientRequest.headers().forEach((name, values) -> values.forEach(value -> LOGGER.info("{}={}", name, value)));
        return Mono.just(clientRequest);
    });
}

还有如下代码,创建用户对象和包含用户对象的命令,然后调用webclient发送请求

@Autowired
private BaseWebClient baseWebClient;
@Override
public void saveOrUpdateUser() {
        UserPayload userPayload = new UserPayload();
        userPayload.setUserId(111L);
        userPayload.setCreatedAt(ZonedDateTime.now(DateTimeProps.systemTimeZone));
        UserCommand userCommand = new UserCommand();
        userCommand.setUser(userPayload);
        baseWebClient.sendRequest(HttpMethod.POST, "application/json",
            Stream.of(userCommand).collect(Collectors.toList()),
            "http://localhost:8080",
            "/users").onStatus(HttpStatus::isError, clientResponse -> {
        throw new WebClientUserSaveOrUpdateeFailedException("Exception when trying to update user state")
        .bodyToMono(String.class);
    });
}

用户负载:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserPayload {
  Long userId;
  ZonedDateTime createdAt;
}

用户命令:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserCommand {
     @JsonProperty("user")
     UserPayload user;
}

Json 正在等待我的其他应用程序(我正在向其发送请求):

[
  { "user":
            { 
              "userId": 1,
              "createdAt": "2019-05-16T08:24:46.412Z"
            } 
  }
]

使用:Spring boot 2,Lombok(对于 getter/setter),gradle 当我尝试发送请求时,没有任何反应。甚至也不例外。 我尝试了非常简单的案例以及同样的问题。 再注意一点,是否可以记录正文?我的意思是不知何故看到最终 json 我想我缺少一些一般性的东西。

在 Reactor nothing happens until you subscribe. retrive() does not actually start the request. As you can see in the example 中,您应该使用其中一种方法将 ResponseSpec 转换为发布者,然后最终订阅该发布者。

根据您使用此方法的方式,您或许可以让 Spring 订阅发布者。 WebFlux 支持模型中的反应类型,这意味着您可以 directly return a Mono 来自 RestController 方法,例如。