Spring WebFlux:如何根据查询参数路由到不同的处理程序函数? [英] Spring WebFlux: How to route to a different handler function based on query parameters?
本文介绍了Spring WebFlux:如何根据查询参数路由到不同的处理程序函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 Spring WebFlux 函数式编程编写个人 API,如何根据查询参数名称路由到不同的处理程序函数?
I am writing a person API using Spring WebFlux functional programming, how to route to different handler functions based on the query param names?
@Bean
public RouterFunction<ServerResponse> route(PersonHandler personHandler) {
return RouterFunctions.route(GET("/people/{id}").and(accept(APPLICATION_JSON)), personHandler::get)
.andRoute(GET("/people").and(accept(APPLICATION_JSON)), personHandler::all)
.andRoute(GET("/people/country/{country}").and(accept(APPLICATION_JSON)), personHandler::getByCountry)
// .andRoute(GET("/people?name={name}").and(accept(APPLICATION_JSON)), personHandler::searchByName)
// .andRoute(GET("/people?age={age}").and(accept(APPLICATION_JSON)), personHandler::searchByAge)
// I am expecting to do something like this
;
}
还是需要在处理函数中处理?喜欢
Or do I need to handle it in the handler function? like
public Mono<ServerResponse> searchPeople(ServerRequest serverRequest) {
final Optional<String> name = serverRequest.queryParam("name");
final Optional<String> age = serverRequest.queryParam("age");
Flux<People> result;
if(name.isPresent()){
result = name.map(peopleRepository::searchByName)
.orElseThrow();
} else if(age.isPresent()){
result = name.map(peopleRepository::searchByage)
.orElseThrow();
}
return ok().contentType(MediaType.APPLICATION_JSON).body(result, People.class);
}
最好的方法是什么?
谢谢
推荐答案
您可以创建自己的 RequestPredicate
并使用现有的基础架构(通过将其插入到 and()
):
You can create your own RequestPredicate
and use the existing infrastructure (by plugging it into a and()
):
public static RequestPredicate hasQueryParam(String name) {
return RequestPredicates.queryParam(name, p -> StringUtils.hasText(p));
}
这篇关于Spring WebFlux:如何根据查询参数路由到不同的处理程序函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文