我有一个服务,它返回一个包含延迟信息的值。
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"能力。
您可以在flatMap
中使用Mono.fromCallable
+delayElement
:
return authService.authenticate(authenticationRequest, headers)
.flatMap(authenticationResponse -> {
return Mono.fromCallable(() -> authenticationResponse.getOperationResponse())
.delayElement(authenticationResponse.getDelay())
});
有一件事要注意……在这种情况下,您不能将ServerHttpResponse
作为参数传递,但是您有ServerWebExchange
,它具有请求和响应以及标头。完整的解决方案是
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()));
}
尝试根据您的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());
});
}
如果不工作请告诉我。我再想别的办法。