11.2 定义函数式请求处理程序
11.2 定义函数式请求处理程序
首先,任何基于注解的编程都涉及到注解应该对做什么以及如何做定义上区分。注解本身定义了什么;如何在框架代码的其他地方定义。当涉及到任何类型的定制或扩展时,这会使编程模型复杂化,因为这样的更改需要在注解外部的代码中工作。此外,调试这样的代码是很棘手的,因为不能在注解上设置断点。
另外,随着
这个新的编程模型更像是一个库,而不是一个框架,允许你将请求映射到不带注解的处理代码。使用
- RequestPredicate —— 声明将会被处理的请求类型
- RouteFunction —— 声明一个匹配的请求应该如何被路由到处理代码中
- ServerRequest —— 表示
HTTP 请求,包括对头和正文信息的访问 - ServerResponse —— 表示
HTTP 响应,包括头和正文信息
作为将所有这些类型组合在一起的简单示例,请考虑以下
package demo;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
import static org.springframework.web.reactive.function.server.ServerResponse.ok;
import static reactor.core.publisher.Mono.just;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.RouterFunction;
@Configuration
public class RouterFunctionConfig {
@Bean
public RouterFunction<?> helloRouterFunction() {
return route(GET("/hello"),
request -> ok().body(just("Hello World!"), String.class));
}
}
首先要注意的是,已经选择静态地导入几个
在这个
/hello
路径的
至于
如前所述,/bye
的
@Bean
public RouterFunction<?> helloRouterFunction() {
return route(GET("/hello"), request -> ok().body(just("Hello World!"), String.class))
.andRoute(GET("/bye"), request -> ok().body(just("See ya!"), String.class));
}
为了演示函数式编程模型如何在实际应用程序中使用,让我们将
@Configuration
public class RouterFunctionConfig {
@Autowired
private TacoRepository tacoRepo;
@Bean
public RouterFunction<?> routerFunction() {
return route(GET("/design/taco"), this::recents)
.andRoute(POST("/design"), this::postTaco);
}
public Mono<ServerResponse> recents(ServerRequest request) {
return ServerResponse.ok()
.body(tacoRepo.findAll().take(12), Taco.class);
}
public Mono<ServerResponse> postTaco(ServerRequest request) {
Mono<Taco> taco = request.bodyToMono(Taco.class);
Mono<Taco> savedTaco = tacoRepo.save(taco);
return ServerResponse
.created(URI.create(
"http://localhost:8080/design/taco/" +
savedTaco.getId()))
.body(savedTaco, Taco.class);
}
}
如你所见,/design/taco
的/design
的
更突出的是路由是由方法引用处理的。当
根据你的需要,/design/taco
的/design
的