如何为来自 Mono 的数据添加延迟?

How do I add a delay with data from the Mono?

我有一个服务正在返回一个包含延迟信息的值。

  public Mono<R> authenticate(
      A authenticationRequest,
      @RequestHeader Map<String, String> headers,
      ServerHttpResponse serverHttpResponse) {

    final AuthServiceResponse<R> authenticationResponse = authService.authenticate(authenticationRequest, headers);
    serverHttpResponse.setStatusCode(authenticationResponse.getStatusCode());
    return Mono.just(authenticationResponse.getOperationResponse())
        .delayElement(authenticationResponse.getDelay());
  }

我想尝试将其转换为反应式我已经做到了这一点...

  public Mono<R> authenticate(
      A authenticationRequest,
      @RequestHeader Map<String, String> headers,
      ServerHttpResponse serverHttpResponse) {

    return authService.authenticate(authenticationRequest, headers)
            .map(authenticationResponse->{
              serverHttpResponse.setStatusCode(authenticationResponse.getStatusCode());          
              return authenticationResponse.getOperationResponse()
            });
      ...

但我不确定如何添加“delayElement”功能。

试试这个,根据您的 authenticationResponse.getDelay() 值添加延迟

public Mono<Object> authenticate(Object authenticationRequest,@RequestHeader Object headers,
        Object serverHttpResponse) {

    return authenticate(authenticationRequest,headers)
            .flatMap(authenticationResponse -> {
                Mono<String> delayElement = Mono.just("add delay")
                        .delayElement(Duration.ofSeconds(authenticationResponse.getDelay()));
                Mono<Object> actualResponse =Mono.just(authenticationResponse.getOperationResponse());
                return Mono.zip(delayElement,actualResponse).map(tupleT2 -> tupleT2.getT2());
            });

}

如果它不起作用,请告诉我。我会尝试找到其他方法。

您可以像这样在 flatMap 中使用 Mono.fromCallable + delayElement

return authService.authenticate(authenticationRequest, headers)
         .flatMap(authenticationResponse -> {
           return Mono.fromCallable(() -> authenticationResponse.getOperationResponse())
                      .delayElement(authenticationResponse.getDelay())
            });

需要注意的一件事...在这种情况下您不能将 ServerHttpResponse 作为参数传递,但是您有 ServerWebExchange,其中包含请求和响应以及 headers。完整的解决方案是

public Mono<R> authenticate(
      @RequestBody SimpleAuthenticationRequest authenticationRequest,
      ServerWebExchange serverWebExchange) {

    return authService
        .authenticate(authenticationRequest, serverWebExchange.getRequest().getHeaders())
        .doOnNext(
            serviceResponse ->
                serverWebExchange.getResponse().setStatusCode(serviceResponse.getStatusCode()))
        .flatMap(
            serviceResponse ->
                Mono.fromCallable(serviceResponse::getOperationResponse)
                    .delayElement(serviceResponse.getDelay()));
}