当使用Spring WebClient重试时,添加新的头。

问题描述 投票:2回答:1
webclientbuilder.baseUrl(url)
                .defaultHeaders(headers -> headers.addAll(requestHeader))
                .build()
                .post()
                .uri("/uri")
                .bodyValue(data)
                .exchange()
                .flatMap(response  -> {
                                if(response.statusCode() == HttpStatus.UNAUTHORIZED){
                                                //retry with updated token in header
                                }
                })
                //return bodyToMono of specific object when retry is done or if
                //response status is 2xx

有什么处理方法的建议,请多多指教! 就像评论里说的,我需要在重试帖子请求前把新的token添加到头中,如果有一个状态码为UNAUTHORIZED,如果状态码为2xx,则返回bodyToMono。

spring spring-boot request-headers spring-retry spring-webclient
1个回答
1
投票

你可以通过在web客户端中添加一个过滤器来解决这个问题。

public ExchangeFilterFunction retryOn401() {
    return (request, next) -> next.exchange(request)
            .flatMap((Function<ClientResponse, Mono<ClientResponse>>) clientResponse -> {
                if (clientResponse.statusCode() == HttpStatus.UNAUTHORIZED) {
                    return authClient.getUpdatedToken() //here you get a Mono with a new & valid token
                            .map(token -> ClientRequest
                                    .from(request)
                                    .headers(headers -> headers.replace("Authorization", Collections.singletonList("Bearer " + token)))
                                    .build())
                            .flatMap(next::exchange);
                } else {
                    return Mono.just(clientResponse);
                }
            });
}

因此,当web客户端重试未经授权的请求时,它可以获得一个新的令牌,并在执行重试之前将其设置在头中,确保将其添加到web客户端中。

webclientbuilder.baseUrl(url)
            .defaultHeaders(headers -> headers.addAll(requestHeader))
            .filter(retryOn401())
            .build();
© www.soinside.com 2019 - 2024. All rights reserved.