SpringWebflux实现方式有两种:注解编程模型和函数式编程模型
SpringWebflux(基于注解编程模型)
使用注解编程模型方式,和之前SpringMVC使用相似的,只需要把相关依赖配置到项目中,SpringBoot自动配置相关运行容器,默认情况下使用Netty服务器
第一步:创建SpringBoot工程,引入Webflux依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
第二步:配置启动端口号
server.port=8082
第三步:创建包和相关类
实体类
public class User {
private String name;
private String gender;
private Integer age;
public User() {
}
public User(String name, String gender, Integer age) {
this.name = name;
this.gender = gender;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
创建接口定义操作的方法
//用户操作接口
public interface UserService {
//根据id查询用户
Mono<User> getUserById(int id);
//查询所有用户
Flux<User> getAll();
//添加用户
Mono<Void> saveUser(Mono<User> userMono);
}
接口实现类
@Service
public class UserServiceImpl implements UserService {
//创建map集合 测试数据
private final Map<Integer,User> users = new HashMap<>();
public UserServiceImpl(){
this.users.put(1,new User("Tom","男",11));
this.users.put(2,new User("Jack","男",40));
this.users.put(3,new User("Lucy","女",18));
}
//根据id查询
@Override
public Mono<User> getUserById(int id) {
return Mono.justOrEmpty(this.users.get(id));
}
//查询所有用户
@Override
public Flux<User> getAll() {
return Flux.fromIterable(this.users.values());
}
//添加用户
@Override
public Mono<Void> saveUser(Mono<User> userMono) {
return userMono.doOnNext(person -> {
//向map集合防放数据
int id = users.size() + 1;
users.put(id,person);
}).thenEmpty(Mono.empty());
}
}
创建Controller
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/user/{id}")
public Mono<User> getUserById(@PathVariable int id){
return userService.getUserById(id);
}
@GetMapping("/users")
public Flux<User> getUserById(){
return userService.getAll();
}
@GetMapping("/user")
public Mono<Void> saveUser(@RequestBody User user){
Mono<User> userMono = Mono.just(user);
return userService.saveUser(userMono);
}
}
●说明
SpringMVC的方式实现,是同步阻塞的方式,基于SpringMVC+Servlet+Tomcat
SpringWebflux的方式实现,是异步非阻塞方式,基于SpringWebflux+Reactor+Netty