Spring WebFlux:如何根据查询参数路由到其他处理程序函数?

时间:2019-05-24 18:20:23

标签: spring functional-programming reactive-programming spring-webflux

我正在使用Spring WebFlux函数编程编写人员API,如何根据查询参数名称路由到不同的处理函数?

    @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
                ;
    }

还是我需要在处理程序函数中处理它? 喜欢

    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);
    }

最好的方法是什么?

谢谢

1 个答案:

答案 0 :(得分:1)

您可以创建自己的RequestPredicate并使用现有的基础结构(通过将其插入and()):

public static RequestPredicate hasQueryParam(String name) {
  return RequestPredicates.queryParam(name, p -> StringUtils.hasText(p));
}