我一直在寻找以下用例的解决方案,但没有成功,希望有人能帮忙:
假设以下用例。我需要调用客户API (customerApi
) ,并且此API需要一个可能已过期的Bearer
令牌。如果当我调用customerApi
时该令牌已过期,则customerApi
将返回401
响应。
我的要求是:如果收到了401
响应,我只想重试一次,并调用获取新Bearer
令牌的方法。如果重试仍然返回401
,则需要抛出一个Exception
异常。
获取Bearer
令牌的方法:
private String getToken() {
return oAuthService.getToken();
}
使用webClient
调用customerApi
(customerWebClient
是使用WebClient.Builder
创建的bean):
public Customer getCustomerById(String customerId, String token) {
return customerWebClient.get()
.uri("myurl/customers/{customerId}, customerId)
.headers(httpHeaders -> {
httpHeaders.add(HttpHeaders.AUTHORIZATION, "Bearer " + token);
})
.retrieve()
.bodyToMono(Customer.class)
.onErrorResume(WebClientResponseException.NotFound.class, notFound ->
Mono.error(new MyCustomException()))
.block();
}
似乎
retryWhen
只能用于升级超时。所以我希望有人知道如何实现这个用例^^谢谢你的帮助 :)
编辑:
我尝试使用
reactor-extra
中的retryWhen(Retry.onlyIf(...))
,但是这个包中的老旧的retryWhen
现在已经被弃用了(基于Adding a retry all requests of WebClient的解决方案)。
retryWhen
的https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html#retryWhen-reactor.util.retry.Retry-上没有看到任何弃用通知。 - undefined