Spring WebFlux:如何根据查询参数路由到不同的处理函数?
Spring WebFlux: How to route to a different handler function based on query parameters?
我正在写一个人 API 使用 Spring WebFlux 函数式编程,如何根据查询参数名称路由到不同的处理函数?
@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
;
}
还是需要在handler函数中处理?
喜欢
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()
):
public static RequestPredicate hasQueryParam(String name) {
return RequestPredicates.queryParam(name, p -> StringUtils.hasText(p));
}
我正在写一个人 API 使用 Spring WebFlux 函数式编程,如何根据查询参数名称路由到不同的处理函数?
@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
;
}
还是需要在handler函数中处理? 喜欢
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()
):
public static RequestPredicate hasQueryParam(String name) {
return RequestPredicates.queryParam(name, p -> StringUtils.hasText(p));
}