Spring WebFlux and Spring MVC

What is a WebFlux

  • Is an asynchronous, non-blocking Web framework that takes full advantage of the hardware resources of multi-core cpus to handle large numbers of concurrent requests
  • Advantages: Reactive programming internally, based on a Reactor base, asynchronous and event-driven, allows us to increase throughput and scalability without scaling hardware resources.
  • It does not shorten the response time of the interface; it only improves throughput and scalability.

Application scenarios

  • It is particularly suited for IO intensive services such as microservices gateways.
  • PS: IO intensive includes disk IO intensive and network IO intensive. Microservice gateway belongs to network IO intensive. The asynchronous non-blocking programming model can significantly improve the throughput of gateway forwarding downstream services.

WebFlux or Spring MVC

  • WebFlux is not an alternative to Spring MVC! Although WebFlux can also be run on Servlet containers (Servlet 3.1+ or higher), WebFlux is mainly used in asynchronous non-blocking programming models, whereas Spring MVC is synchronous blocking. If you currently use a lot of asynchronous solutions in the Spring MVC framework, then WebFlux is what you want, otherwise, using Spring MVC is your first choice.

  • In microservices architecture, Spring MVC and WebFlux can be mixed. For example, as mentioned, WebFlux can be used for IO intensive services such as gateways.

Similarities and differences

Similarities and differences

Note:

  • Because Spring MVC uses synchronous blocking, it is more convenient for developers to write functional codes, Debug tests and so on. Generally speaking, if Spring MVC can meet the scenarios, it should try not to use WebFlux;
  • By default, WebFlux uses Netty as the server.
  • The mainstream database is basically ok, there are currently projects to support mysql,https://r2dbc.io/ (to be careful to use, after all, R2DBC is still experimental);

How is WebFlux distributed

  • Springmvc is via DispatcherServlet, while WebFlux is DispatcherHandler, which implements the WebHandler interface:
webHandler
handle
  • ① : The ServerWebExchange object placed each HTTP request response information, including parameters, etc.;
  • (2) If the entire interface mapping set is empty, a “Not Found” error will be created.
  • ③ : Obtain the corresponding handlerMapping according to the specific request address;
  • (4) : call specific business methods, that is, we define the interface method;
  • ⑤ : process the returned results;