Spring webflux Spring WebClient:重试中的调用方法
我一直在寻找以下用例的解决方案,但没有成功,我希望有人能提供帮助: 假设以下用例。我需要调用一个客户Api(Spring webflux Spring WebClient:重试中的调用方法,spring-webflux,spring-webclient,reactor-netty,Spring Webflux,Spring Webclient,Reactor Netty,我一直在寻找以下用例的解决方案,但没有成功,我希望有人能提供帮助: 假设以下用例。我需要调用一个客户Api(customerApi),此Api需要一个Bearer令牌,当我调用customerApi时,该令牌可能已过期。如果令牌已过期,则customerApi返回401响应 我想做的是,如果我收到401并调用该方法以获取新的承载令牌,则只重试一次。如果重试仍然返回401,我需要抛出一个异常 获取承载令牌的方法: private String getToken() { return oAu
customerApi
),此Api需要一个Bearer
令牌,当我调用customerApi
时,该令牌可能已过期。如果令牌已过期,则customerApi
返回401
响应
我想做的是,如果我收到401
并调用该方法以获取新的承载
令牌,则只重试一次。如果重试仍然返回401
,我需要抛出一个异常
获取承载
令牌的方法:
private String getToken() {
return oAuthService.getToken();
}
调用customerApi
的webClient
用法(customerWebClient
是使用webClient.Builder
创建的bean):
似乎retryWhen
只能用于升级超时。所以我希望有人知道如何实现这个用例^^
谢谢你的帮助:)
编辑:
我尝试使用reactor extra
中的retryWhen(Retry.onlyIf(…)
,但是这个包中的好的retryWhen
现在已经被弃用了(解决方案基于:)该方法
public final Mono retryWhen(函数)我在任何retryWhen
完美解决方案上都没有看到任何弃用通知!Thx很多,因为这不是正确的方法,与我需要实现的实际用例相比,我简化了主题。确实是很好的解决方案,非常感谢@Isank
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();
}