我正在尝试使用 Spring WebClient
构建重试逻辑。我试图解决的问题非常简单。我正在调用 API 端点以获取一些值。如果 API 返回错误并显示 401 响应,那么我将不得不调用令牌服务并更新我的令牌并使用新令牌并进行相同的 API 调用。
一般的伪代码是
try {
GET /locations data
} catch(401 Unauthorized) {
POST /token and get renew Token --> This is another WebClient API call With New Token
call again GET /locations and return value
} catch (Another Exception) {
throw Application Error
}
这是我正在尝试执行的 Spring 代码,但它看起来似乎不起作用。 关于如何做的任何建议。
public List<Location> getLocations(final User user) {
if (null == user) {
throw new ApplicationException("User cannot be null");
}
if (null == user.getHoneyWellLinkToken()) {
throw new ApplicationException(String.format("%s has not linked the account with Honeywell",user.getusername()));
}
List<Location> locations = getLocationsAPI(user).block();
return locations;
}
private Mono<List<Location>> getLocationsAPI(final User user) {
String endpoint = config.getapi().getLocationsEndpoint()
.concat("?apikey=")
.concat(config.getcredentials().getclientId());
return WebClient.builder().baseUrl(endpoint)
.build()
.get()
.headers(httpHeaders -> httpHeaders.setBearerauth(user.getHoneyWellLinkToken().getaccessToken()))
.retrieve()
.bodyToFlux(Location.class)
.collectList()
.doOnError(err -> {
WebClient.builder().baseUrl(endpoint)
.build()
.get()
.headers(httpHeaders -> httpHeaders.setBearerauth(honeywellService.renewToken(user).block().getHoneyWellLinkToken().getaccessToken()))
.retrieve().bodyToFlux(Location.class);
});
}
此代码托管在 GitHub https://github.com/reflexdemon/home-use/blob/main/src/main/java/io/vpv/homeuse/service/HoneywellThermostatService.java