spring webflux 的案例
时间: 2023-09-02 19:14:21 浏览: 52
以下是一个简单的 Spring WebFlux 案例:
1. 首先,需要创建一个 Maven 项目,并在 pom.xml 文件中添加以下依赖项:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
```
2. 接下来,创建一个简单的 REST API,用于返回一些用户数据。在 src/main/java 目录下创建一个名为 UserController 的类:
```
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
@RestController
public class UserController {
@GetMapping("/users")
public Flux<User> getUsers() {
return Flux.just(
new User("John", "Doe"),
new User("Jane", "Doe"),
new User("Bob", "Smith")
);
}
public static class User {
private String firstName;
private String lastName;
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
}
```
3. 启动 Spring Boot 应用程序并访问 http://localhost:8080/users,即可获取用户数据。
这是一个简单的 Spring WebFlux 案例,它使用了 Reactor 的组件来实现响应式编程。使用 Spring WebFlux,可以轻松地构建响应式 Web 应用程序,以满足大量并发访问的需求。