英文:
Spring webflux - Routing
问题
我正在使用Spring Boot 2.3.3.RELEASE,并且正在使用WebFlux。使用以下路由配置:
@Bean
public RouterFunction<ServerResponse> itemRoute() {
return RouterFunctions.route(POST("/api/v1/item").and(accept(APPLICATION_JSON)), itemHandler::createItem)
.andRoute(GET("/api/v1/item/{itemId}").and(accept(APPLICATION_JSON)), itemHandler::getItemById)
.andRoute(GET("/api/v1/item/list").and(accept(APPLICATION_JSON)), itemHandler::getItems);
}
当我访问 /api/v1/item/1
时,它按预期工作。
但是,访问 /api/v1/list
时,也会进入 getItemById
而不是 getItems
。/api/v1/item/list
也被视为 /api/v1/item/{itemId}
,并且将 "list" 视为 itemId。
这里是否有什么问题?
英文:
I am using Spring boot 2.3.3.RELASE and using webflux. Using the below router config.
@Bean
public RouterFunction<ServerResponse> itemRoute() {
return RouterFunctions.route(POST("/api/v1/item").and(accept(APPLICATION_JSON)), itemHandler::createItem)
.andRoute(GET("/api/v1/item/{itemId}").and(accept(APPLICATION_JSON)), itemHandler::getItemById)
.andRoute(GET("/api/v1/item/list").and(accept(APPLICATION_JSON)), itemHandler::getItems);
}
When I hit /api/v1/item/1
---> It works as expected.
But, hitting /api/v1/list
also goes to getItemById
instead of getItems
. /api/v1/item/list
also considered as /api/v1/item/{itemId}
and list is coming as itemId.
Anything wrong with this?
答案1
得分: 2
Spring andRoute
的文档
> 返回一个组合的路由函数,如果此路由不匹配并且给定的请求谓词适用,则路由到给定的处理程序函数。
这里的关键词是 组合。这意味着您可以声明多个路由,所有这些路由都必须一起匹配,以触发路由。
您可能正在寻找的可能只是使用普通的 route
构建函数。
从 Spring 文档中获取的示例:
RouterFunction<ServerResponse> route = route()
.GET("/person/{id}", accept(APPLICATION_JSON), handler::getPerson)
.GET("/person", accept(APPLICATION_JSON), handler::listPeople)
.POST("/person", handler::createPerson)
.add(otherRoute)
.build();
或者您可以使用 path
构建函数作为另一个选项。
RouterFunction<ServerResponse> route = route()
.path("/api/person", builder -> builder
.POST( ...)
.GET( ... )
.GET( ... )
).build())
.build();
英文:
Spring documentation for andRoute
> Return a composed routing function that routes to the given handler function if this route does not match and the given request predicate applies.
The key word here is composed. It means that you can declare multiple routes that all together must match together for the route to trigger.
what you are looking for is probably just using the plain route
builder function.
Taken example from the spring documentation:
RouterFunction<ServerResponse> route = route()
.GET("/person/{id}", accept(APPLICATION_JSON), handler::getPerson)
.GET("/person", accept(APPLICATION_JSON), handler::listPeople)
.POST("/person", handler::createPerson)
.add(otherRoute)
.build();
or you could use the path
builder function is another option.
RouterFunction<ServerResponse> route = route()
.path("/api/person", builder -> builder
.POST( ...)
.GET( ... )
.GET( ... )
).build())
.build()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论