diff --git a/spring/webflux/spring webflux.md b/spring/webflux/spring webflux.md index eac55bf..9021b13 100644 --- a/spring/webflux/spring webflux.md +++ b/spring/webflux/spring webflux.md @@ -33,6 +33,10 @@ - [Annotated Controllers](#annotated-controllers) - [@Controller](#controller) - [AOP](#aop) + - [Functional Endpoint](#functional-endpoint) + - [Overview](#overview) + - [Immutable](#immutable) + - [Router Function](#router-function) # Spring Webflux @@ -481,3 +485,61 @@ public class HelloController { 对于针对controller的aop,推荐使用`class-based proxy`,可以使用`@EnableTransactionManagement(proxyTargetClass=true)`来实现。 +## Functional Endpoint +`Webflux.fn`是一个轻量级的函数式编程模型,方法用于对请求进行路由和处理。其和基于注解的编程模型一致,都基于相同的reactive core。 + +### Overview +在`Webflux.fn`中,http请求被`HandlerFunction`处理,`HandlerFunction`接收ServerRequest并且返回一个`delayed ServerResponse`(`Mono`)。 + +### Immutable +对于函数时编程模型,`request对象和response对象都是不可变的`。 + +> 一旦reqeust或response对象被创建,其内部状态都无法被直接修改,任何试图对其“修改”的操作都会返回一个新的对象,并且保证原有对象内容不变。 + +由于request和response对象是不可变的,其天然为线程安全的。 + +### Router Function +incoming requests将会被`RouterFunction`路由到handler function,`RouterFunction`接收一个`ServerRequest`并且返回一个`delayed HandlerFunction`。 + +如果存在RouterFunction与request匹配时,其将返回一个handler function;`如果没有任何RouterFunction与请求相匹配,将返回一个空的Mono`。 + +`RouterFunction`的作用和`@RequestMapping`注解相同。 + +`RouterFunctions.route()`方法提供了一个便于创建router的builder,示例如下: +```java +import static org.springframework.http.MediaType.APPLICATION_JSON; +import static org.springframework.web.reactive.function.server.RequestPredicates.*; +import static org.springframework.web.reactive.function.server.RouterFunctions.route; + +PersonRepository repository = ... +PersonHandler handler = new PersonHandler(repository); + +RouterFunction route = route() (1) + .GET("/person/{id}", accept(APPLICATION_JSON), handler::getPerson) + .GET("/person", accept(APPLICATION_JSON), handler::listPeople) + .POST("/person", handler::createPerson) + .build(); + + +public class PersonHandler { + + // ... + + public Mono listPeople(ServerRequest request) { + // ... + } + + public Mono createPerson(ServerRequest request) { + // ... + } + + public Mono getPerson(ServerRequest request) { + // ... + } +} +``` +运行RouterFunction的其中一种方式是将其转化为`HttpHandler`,并将其指定给对应的server adapter: +- `RouterFunctions.toHttpHandler(RouterFunction)` +- `RouterFunctions.toHttpHandler(RouterFunction, HandlerStrategies)` + +