我有一個服務回傳一個包含延遲資訊的值。
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”功能。
uj5u.com熱心網友回復:
您可以在這樣的范圍內使用Mono.fromCallable :delayElementflatMap
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()));
}
uj5u.com熱心網友回復:
嘗試根據您的 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());
});
}
讓我知道它是否不起作用。我會嘗試尋找其他方式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/464983.html
標籤:爪哇 春天 spring-webflux 项目反应堆
