Spring WebClient实现401错误时刷新令牌并重试逻辑的方案咨询
基于Spring WebClient实现401触发令牌刷新并重试的方案
现有代码问题根因
doOnError属于副作用操作符,仅用于执行日志、埋点这类无返回值的逻辑,无法替换原流的错误信号,你在该方法内编写的重试请求不会被订阅执行,所以没有效果- 未对错误类型做过滤,所有异常都会进入重试分支,不符合仅处理401未授权响应的需求
- 在响应式流内部调用
block()会破坏非阻塞特性,可能引发线程阻塞、死锁等问题 - 每次请求都新建
WebClient实例存在不必要的性能开销,建议复用预构建的实例
修正后实现方案
核心使用onErrorResume操作符捕获指定异常,并返回新的请求流实现重试逻辑,代码示例如下:
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())); } return getLocationsAPI(user).block(); } private Mono<List<Location>> getLocationsAPI(final User user) { String endpoint = config.getApi().getLocationsEndpoint() .concat("?apikey=") .concat(config.getCredentials().getClientId()); // 首次调用位置接口 return sendLocationRequest(endpoint, user.getHoneyWellLinkToken().getAccessToken()) // 仅捕获401未授权异常 .onErrorResume(WebClientResponseException.Unauthorized.class, err -> // 先刷新令牌,再用新令牌重试调用原接口 honeywellService.renewToken(user) .flatMap(renewedUser -> sendLocationRequest(endpoint, renewedUser.getHoneyWellLinkToken().getAccessToken())) ) // 其他异常统一转换为应用错误抛出 .onErrorMap(err -> new ApplicationException("获取位置信息失败", err)); } // 抽离公共请求逻辑,避免重复代码 private Mono<List<Location>> sendLocationRequest(String endpoint, String accessToken) { // 生产环境建议将WebClient作为单例Bean注入复用,无需每次新建 return WebClient.builder() .baseUrl(endpoint) .build() .get() .headers(httpHeaders -> httpHeaders.setBearerAuth(accessToken)) .retrieve() .bodyToFlux(Location.class) .collectList(); }
可选优化点
- 把
WebClient实例注册为Spring全局Bean复用,减少重复创建的性能开销 - 如果需要支持多次重试场景,可搭配
retry操作符配置重试次数与退避策略 - 如果上层调用方也支持响应式编程,可去掉
getLocations方法中的block()调用,直接返回Mono<List<Location>>提升吞吐量
内容的提问来源于stack exchange,提问作者reflexdemon
相关产品推荐
相关产品推荐

