如何在WebClient的ExchangeFilterFunction中使用Flatmap?

时间:2019-05-05 01:19:38

标签: spring-boot webclient spring-webflux

我想使用ExchangeFilterFunction检查状态代码以了解令牌是否已过期。如果是这样,我将获取新令牌并重试请求。但是,当我运行代码时,refreshToken()只会无限循环,并且永远不会返回实际的令牌。

    private ExchangeFilterFunction errorHandlingFilter() {
        return (request, next) -> next.exchange(request)
                .flatMap((Function<ClientResponse, Mono<ClientResponse>>) clientResponse -> {
                    if (clientResponse.statusCode().value() == expired code) {

                        return refreshToken().flatMap(token -> {
                            log.info("THE TOKEN IS: " + token.getAccess_token());
                            ClientRequest retryRequest = ClientRequest.from(request)
                                    .header("Authorization", "Bearer " + token.getAccess_token()).build();
                            return next.exchange(retryRequest);
                        });

                    } else {
                        return Mono.just(clientResponse);
                    }
                });
    }
 private Mono<TokenData> refreshToken() {

        log.info("Calling to refresh token");

        return webClient.post()
                .uri("someURL")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .header("Authorization", "Basic something")
                .accept(MediaType.APPLICATION_JSON)
                .body(
                        BodyInserters.fromFormData("grant_type", "something")
                                .with("username","someusername")
                                .with("password","somepass")
                )
                .exchange()
                .flatMap( response -> {
                    log.info("THE TOKEN CODE IS: " + response.getAccess_token());

                    return response.bodyToMono(TokenData.class);
                })
                .switchIfEmpty(Mono.error(new Exception()));
    }

日志显示:

调用刷新令牌

调用刷新令牌

调用刷新令牌

调用刷新令牌

调用刷新令牌

...

它永远不会达到“令牌代码是:”

如果我将调用移出ExchangeFilterFunction,但它在那里需要它,因为它是续签令牌和重试请求的拦截器,它的refreshToken函数可以正常工作。

0 个答案:

没有答案