[英]How can I change the url webClient based on reactor context
Based on a country already added on a webfilter, I need to modify the request to a different server.基于已在 webfilter 上添加的国家/地区,我需要将请求修改到不同的服务器。
I already added the context with the webfilter to the chain, I can see it here, but I didn't find how to modify the received clientRequest based on the signal context on the chain.我已经将带有 webfilter 的上下文添加到了链中,我可以在这里看到它,但是我没有找到如何根据链上的信号上下文修改接收到的 clientRequest。 If anybody already found a way to do that and can help:如果有人已经找到了一种方法并且可以提供帮助:
return webClient
.filter(
ExchangeFilterFunction
.ofRequestProcessor(
new Function<ClientRequest, Mono<ClientRequest>>() {
@Override
public Mono<ClientRequest> apply(ClientRequest clientRequest) {
return Mono.just(
ClientRequest.from(clientRequest).build())
.doOnEach(new Consumer<Signal<ClientRequest>>() {
@Override
public void accept(Signal<ClientRequest> signal) {
var countryContext = signal.getContext()
.getOrEmpty(CountryContext.COUNTRY_CONTEXT_HEADER_REST).get();
System.out.println(countryContext);
}
});
}
}
)
).build();
I found out a way, it's implementing a custom ExchangeFilterFunction
, and using Mono.subscriberContext()
我找到了一种方法,它正在实现自定义ExchangeFilterFunction
,并使用Mono.subscriberContext()
WebClient
.filter((request, next) -> Mono.subscriberContext()
.flatMap(ctx -> {
ClientRequest cr = ClientRequest.from(request)
// manipulate request to the new prefix server
// from the ctx signal.
.build();
return next.exchange(cr);
}
))
Mono.subscriberContext()
is deprecated and will be removed in Spring Reactor 3.5. Mono.subscriberContext()
已弃用,将在 Spring Reactor 3.5 中删除。 Use Mono.deferContextual()
instead.请改用Mono.deferContextual()
。
In your case:在你的情况下:
WebClient.filter((request, next) ->
Mono.deferContextual(ctx -> {
ClientRequest cr = ClientRequest.from(request)
// manipulate request to the new prefix server
// from the ctx signal.
.build();
return next.exchange(cr);
})
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.