Spring WebFlux 入门指南

发布于:2025-03-07 ⋅ 阅读:(106) ⋅ 点赞:(0)

Spring WebFlux 入门指南

1. 什么是 Spring WebFlux?

Spring WebFlux 是 Spring 5 引入的一个基于 Reactor 的响应式编程框架,它是 Spring MVC 的异步非阻塞替代方案,适用于高并发场景。

2. WebFlux 与 Spring MVC 对比

特性 Spring WebFlux Spring MVC
编程模型 响应式(Reactive Streams) 阻塞式(Servlet API)
适用场景 高并发、低延迟 传统 Web 应用
线程模型 事件驱动(少量线程处理大量请求) 线程池(每个请求占用一个线程)
底层容器 Netty、Undertow、Tomcat Tomcat、Jetty

3. 搭建 Spring WebFlux 项目

3.1 添加依赖

在 Spring Boot 项目中使用 WebFlux,需要添加以下依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

3.2 创建 WebFlux 控制器

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/webflux")
public class WebFluxController {

    @GetMapping("/mono")
    public Mono<String> getMono() {
        return Mono.just("Hello, WebFlux!");
    }

    @GetMapping("/flux")
    public Flux<String> getFlux() {
        List<String> data = Arrays.asList("Hello", "WebFlux", "! ");
        return Flux.fromIterable(data).delayElements(Duration.ofSeconds(1));
    }
}

3.3 运行与测试

启动 Spring Boot 应用,使用 curl 或浏览器访问:

  • http://localhost:8080/webflux/mono -> 返回 Hello, WebFlux!
  • http://localhost:8080/webflux/flux -> 逐个返回 HelloWebFlux!(带 1 秒间隔)

4. 使用 WebClient 进行请求

Spring WebFlux 提供了 WebClient 作为 RestTemplate 的响应式替代方案。

import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

public class WebClientExample {
    public static void main(String[] args) {
        WebClient webClient = WebClient.create("http://localhost:8080");
        
        Mono<String> response = webClient.get()
                .uri("/webflux/mono")
                .retrieve()
                .bodyToMono(String.class);
        
        response.subscribe(System.out::println);
    }
}

5. 总结

Spring WebFlux 适用于高并发、低延迟的场景,使用非阻塞编程模型和 Reactor 响应式流。它提供了 WebClient 作为响应式 HTTP 客户端,可以与 WebFlux 服务器端无缝对接。

欢迎尝试 Spring WebFlux,并在你的应用中体验它的高效和灵活性!


网站公告

今日签到

点亮在社区的每一天
去签到