I have an application implemented using Spring WebFlux, and the routing is done through RouterFunctions. Now I want the controller selection to be based on some customized class dynamically in runtime instead of just static URI pattern or request header, how to do that?
For example: there is a request with path /v1/xyz, today we want to have 60% random requests with that path go to controller A and 40% go to controller B, and tomorrow the percentage will be adjusted to 80% and 20%. So I need a mechanism to dynamically decide which controller the same request goes to, how to do that?
Thank you.
CodePudding user response:
You could use Spring WebFlux Functional Endpoints
a lightweight functional programming model in which functions are used to route and handle requests
that will give you more flexibility and control comparing to controllers.
@Bean
RouterFunction<ServerResponse> xyzRoute() {
return route(POST("/v1/xyz"), req -> handler(req));
}
Mono<ServerResponse> handler(ServerRequest serverRequest) {
return evaluateCondition()
.flatMap(condition -> {
if (Boolean.TRUE.equals(condition)) {
retrun handler1(serverRequest);
} else {
retrun handler2(serverRequest);
}
});
}
Mono<ServerResponse> handler1(ServerRequest serverRequest) {
...
}
Mono<ServerResponse> handler2(ServerRequest serverRequest) {
...
}