【发布时间】:2021-01-28 23:09:17
【问题描述】:
我一直在寻找以下用例的解决方案,但没有成功,希望有人能提供帮助:
假设以下用例。我需要给客户 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 的解决方案)
【问题讨论】:
-
我在任何
retryWhenprojectreactor.io/docs/core/release/api/reactor/core/publisher/… 上都没有看到任何弃用通知
标签: spring-webflux spring-webclient reactor-netty