# 27.2 Spring WebFlux框架

Spring WebFlux是Spring Framework 5.0中引入的新的响应式网络框架。不同与Spring MVC，它不需要Servlet API，是完全异步、非阻塞的，通过[Reactor项目](https://projectreactor.io/)实现了[Reactive Streams](http://www.reactive-streams.org/) 规范。

Spring WebFlux有两种风格：函数式和基于注解。基于注解的风格相当接近于Spring MVC模型，如下所示：

```java
@RestController
@RequestMapping("/users")
public class MyRestController {

    @GetMapping("/{user}")
    public Mono<User> getUser(@PathVariable Long user) {
        // ...
    }

    @GetMapping("/{user}/customers")
    public Flux<Customer> getUserCustomers(@PathVariable Long user) {
        // ...
    }

    @DeleteMapping("/{user}")
    public Mono<User> deleteUser(@PathVariable Long user) {
        // ...
    }

}
```

“WebFlux.fn”——函数式变体，从请求的实际处理中分离了路由配置，如下所示：

```java
@Configuration
public class RoutingConfiguration {

    @Bean
    public RouterFunction<ServerResponse> monoRouterFunction(UserHandler userHandler) {
        return route(GET("/{user}").and(accept(APPLICATION_JSON)), userHandler::getUser)
                .andRoute(GET("/{user}/customers").and(accept(APPLICATION_JSON)), userHandler::getUserCustomers)
                .andRoute(DELETE("/{user}").and(accept(APPLICATION_JSON)), userHandler::deleteUser);
    }

}

@Component
public class UserHandler {

    public Mono<ServerResponse> getUser(ServerRequest request) {
        // ...
    }

    public Mono<ServerResponse> getUserCustomers(ServerRequest request) {
        // ...
    }

    public Mono<ServerResponse> deleteUser(ServerRequest request) {
        // ...
    }
}
```

WebFlux是Spring框架的一部分。详细信息请查看它的[参考文档](https://docs.spring.io/spring/docs/5.0.4.RELEASE/spring-framework-reference/web-reactive.html#webflux-fn)。

**注** 你可以定义多个`RouterFunction` bean来模块化路由的定义。如果你需要应用优先级，可以给bean排序。

给你的应用添加`spring-boot-starter-webflux`模块，开始使用。

**注** 在你的应用里同时添加`spring-boot-starter-web`和`spring-boot-starter-webflux`模块，会使Spring Boot自动配置Spring MVC，而不是WebFlux。这种行为是因为许多Spring开发者为了使用响应式的`WebClient`，往他们的Spring MVC应用里添加`spring-boot-starter-webflux`。你可以设置应用类型为`SpringApplication.setWebApplicationType(WebApplicationType.REACTIVE)`，强制Spring Boot自动配置WebFlux。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jack80342.gitbook.io/spring-boot/iv.-spring-boot-features/27.-developing-web-applications/27.2-the-spring-webflux-framework.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
