如何在使用SpringBoot WebClient时拦截请求

u5rb5r59  于 2023-08-04  发布在  Spring
关注(0)|答案(3)|浏览(205)

我正在尝试使用WebClient调用我的restServices。在RestTemplate之前,我们定义了ClientHttpRequestInterceptor,并将其附加到RestTemplate,以拦截和修改请求。对于WebClient,有没有办法做到这一点?
谢谢你,
-Sreeni

h4cxqtbf

h4cxqtbf1#

使用WebClient Builder时,可以使用filter()方法传入ExchangeFilterFunction接口的实现。这相当于RestTemplateClientHttpRequestInterceptor
WebClient Builder文档:https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/reactive/function/client/WebClient.Builder.html#filter-org.springframework.web.reactive.function.client.ExchangeFilterFunction-
ExchangeFilterFunction文档:https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/reactive/function/client/ExchangeFilterFunction.html
举例来说:

WebClient webClient = WebClient.builder()
        .baseUrl("http://localhost:8080|)
        .filter(logFilter())
        .build();

private ExchangeFilterFunction logFilter() {
    return (clientRequest, next) -> {
        logger.info("External Request to {}", clientRequest.url());
        return next.exchange(clientRequest);
    };
}

字符串

pbossiut

pbossiut2#

在我的情况下,我需要从传入的请求中获取一些头,并把它们放到我的请求中。我找到了我需要的here
首先需要一个过滤器

/**
 * ReactiveRequestContextFilter
 *
 * @author L.cm
 */
@Configuration
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
public class ReactiveRequestContextFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        return chain.filter(exchange)
        .subscriberContext(ctx -> ctx.put(ReactiveRequestContextHolder.CONTEXT_KEY, request));
    }
}

字符串
ReactiveRequestContextHolder

/**
 * ReactiveRequestContextHolder
 *
 * @author L.cm
 */
public class ReactiveRequestContextHolder {
    static final Class<ServerHttpRequest> CONTEXT_KEY = ServerHttpRequest.class;

    /**
     * Gets the {@code Mono<ServerHttpRequest>} from Reactor {@link Context}
     * @return the {@code Mono<ServerHttpRequest>}
     */
    public static Mono<ServerHttpRequest> getRequest() {
        return Mono.subscriberContext()
            .map(ctx -> ctx.get(CONTEXT_KEY));
    }

}


最后像Michael McFadyen说你需要配置一个ExchangeFilterFunction,在我的例子中,我需要Auth和origin:

private ExchangeFilterFunction headerFilter() {
    return (request, next) -> ReactiveRequestContextHolder.getRequest()
            .flatMap(r -> {
                ClientRequest clientRequest = ClientRequest.from(request)
                        .headers(headers -> {
                            headers.set(HttpHeaders.ORIGIN, r.getHeaders().getFirst(HttpHeaders.ORIGIN));
                            headers.set(HttpHeaders.AUTHORIZATION, r.getHeaders().getFirst(HttpHeaders.AUTHORIZATION));
                        })
                        .build();
                return next.exchange(clientRequest);
            });
}


编辑:在新版本的项目中,reactor Mono.subscriberContext()不存在。必须使用Mono.deferContextual(Mono::just)更改,并且使用.contextWrite(ctx -> ...)更改.subscriberContext(ctx -> ...)

hivapdat

hivapdat3#

您可以使用ExchangeFilterFunction并在您正在使用的WebClient示例上配置它。有关更多信息,请参阅Spring Framework参考文档。

相关问题