WebFlux operation of new features in Spring

1 Description

In responsive programming operations, Reactor is a framework that meets the Reactive specification

Reactor has two core classes, Mono and Flux, which implement the interface Publisher and provide rich operators. The Flux object implements the publisher and returns N elements; the Mono implements the publisher and returns 0 or 1 elements.

Both Flux and Mono are publishers of data streams. Both Flux and Mono can send three data signals: element value, error signal, completion signal, error signal and completion signal all represent termination signals, and termination signals are used to tell subscribers about data The end of the stream, the error signal terminates the data stream and passes the error message to the subscriber.

2 Operation Case

1 Introducing dependencies

<dependency>
 <groupId>io.projectreactor</groupId>
 <artifactId>reactor-core</artifactId>
 <version>3.1.5.RELEASE</version>
</dependency>

2 test classes

public class Test{
    
    
    public static void main(String[] args) {
    
    
 // just 方法直接声明
 Flux.just(1,2,3,4);
 Mono.just(1);
 // 其他的方法
 Integer[] array = {
    
    1,2,3,4};
 Flux.fromArray(array);
 
 List<Integer> list = Arrays.asList(array);
 Flux.fromIterable(list);
 Stream<Integer> stream = list.stream();
 Flux.fromStream(stream);
}
}

Signal Features:

  • The error signal and the completion signal are both termination signals and cannot coexist
  • If no element value is sent, but an error or completion signal is sent directly, it means an empty data stream
  • If there is no error signal and no completion signal, it means an infinite data stream

Calling just or other methods is just to declare the data flow, the data flow is not sent out, the data flow will only be triggered after subscription is made, and nothing will happen if you do not subscribe.

such as

 // just 方法直接声明
 Flux.just(1,2,3,4).subscribe(System.out::print);
 Mono.just(1).subscribe(System.out::print);

3 Spring Webflux execution process

1 Spring Webflux is based on Reactor, and the default container is Netty, which is a high-performance NIO framework, an asynchronous and non-blocking framework.

2 The execution process of SpringWebflux is similar to that of SpringMVC. The core controller of SpringWebflux, DispatchHandler, implements the interface WebHandler.

3 DispatcherHandler in SpringWebflux is responsible for request processing

  • DispatcherHandler in SpringWebflux is responsible for request processing
  • HandlerAdapter: really responsible for request processing
  • HandlerResultHandler: response result processing

4 Spring Webflux implements functional programming, which consists of two interfaces:

  • RouterFunction (routing processing)
  • HandlerFunction (handler function)

4 Annotation-based programming

1 Create a Spring Boot project and introduce Webflux dependencies

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

2 Create entity classes

public class User{
    
    
    private String name;
    private String gender;
    private Integer age;
    
    // 省略 构造 setter/getter
}

create interface

public interface UserService{
    
    
    // 根据id查询
    Mono<User> getUserById(int id);
    // 查询所有用户
 	Flux<User> getAllUser();
 	// 添加用户
	Mono<Void> saveUserInfo(Mono<User> user);

}

Implementation class

public class UserServiceImpl implements UserService {
    
    
 // 创建 map 集合存储数据
 private final Map<Integer,User> users = new HashMap<>();
 public UserServiceImpl() {
    
    
 this.users.put(1,new User("lacy","男",20));
 this.users.put(2,new User("may","女",30));
 this.users.put(3,new User("jack","男",50));
 }
 // 根据 id 查询
 @Override
 public Mono<User> getUserById(int id) {
    
    
 return Mono.justOrEmpty(this.users.get(id));
 }
 // 查询多个用户
 @Override
 public Flux<User> getAllUser() {
    
    
 return Flux.fromIterable(this.users.values());
 }

// 添加用户
 @Override
 public Mono<Void> saveUserInfo(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 {
    
    
 // 注入 service
 @Autowired
 private UserService userService;
 // id 查询
 @GetMapping("/user/{id}")
 public Mono<User> geetUserId(@PathVariable int id) {
    
    
 return userService.getUserById(id);
 }
 // 查询所有
 @GetMapping("/user")
 public Flux<User> getUsers() {
    
    
 return userService.getAllUser();
 }
 // 添加
 @PostMapping("/saveuser")
 public Mono<Void> saveUser(@RequestBody User user) {
    
    
 Mono<User> userMono = Mono.just(user);
 return userService.saveUserInfo(userMono);
 }
}

SpringMVC implementation, synchronous blocking method, based on SpringMVC+Servlet+Tomcat

Implemented by SpringWebflux, asynchronous and non-blocking, based on SpringWebflux+Reactor+Netty

Guess you like

Origin blog.csdn.net/ABestRookie/article/details/127341735