Spring WebFlux API 使用教程
1. WebFlux API 简介
Spring WebFlux 是 Spring 5 引入的基于 Reactor 的响应式 Web 框架,适用于构建非阻塞的 REST API。WebFlux 提供了两种编程模型:
- 基于注解(类似 Spring MVC)
- 基于函数式编程(Functional Endpoints)
本教程将介绍如何使用 WebFlux API 来构建高效的 RESTful 服务。
2. 创建 WebFlux 项目
2.1 添加依赖
在 Spring Boot 项目中引入 WebFlux 依赖:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
2.2 配置 WebFlux
Spring WebFlux 默认支持 Netty 作为服务器,但也可运行在 Tomcat、Undertow 等服务器上。无需额外配置即可使用。
3. WebFlux API 开发
3.1 基于注解的 WebFlux API
创建一个 REST 控制器:
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;import java.time.Duration;
import java.util.List;@RestController
@RequestMapping("/users")
public class UserController {@GetMapping("/{id}")public Mono<String> getUserById(@PathVariable String id) {return Mono.just("User: " + id);}@GetMappingpublic Flux<String> getAllUsers() {List<String> users = List.of("Alice", "Bob", "Charlie");return Flux.fromIterable(users).delayElements(Duration.ofSeconds(1));}
}
测试 API:
GET /users/1
-> 返回User: 1
GET /users
-> 逐个返回Alice
、Bob
、Charlie
(每 1 秒返回一个)
3.2 使用 WebClient 进行调用
WebClient 是 WebFlux 提供的响应式 HTTP 客户端。
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;public class WebClientExample {public static void main(String[] args) {WebClient client = WebClient.create("http://localhost:8080");Mono<String> response = client.get().uri("/users/1").retrieve().bodyToMono(String.class);response.subscribe(System.out::println);}
}
4. 基于函数式编程的 WebFlux API
4.1 创建 Handler
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;public class UserHandler {public Mono<ServerResponse> getUser(ServerRequest request) {String userId = request.pathVariable("id");return ServerResponse.ok().bodyValue("User: " + userId);}
}
4.2 定义路由
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;@Configuration
public class RouterConfig {@Beanpublic RouterFunction<ServerResponse> userRoutes(UserHandler handler) {return RouterFunctions.route(GET("/users/{id}"), handler::getUser);}
}
5. 结论
Spring WebFlux 提供了基于注解和函数式编程的方式来构建响应式 API,同时支持 WebClient 进行异步 HTTP 调用。在高并发场景下,WebFlux 具有更好的性能和扩展性。
欢迎尝试 WebFlux API,并根据业务需求选择适合的编程模型!