current position:Home>Spring Webflux tutorial: how to build reactive web applications

Spring Webflux tutorial: how to build reactive web applications

2021-08-25 15:04:30 Old K's Java blog

Spring WebFlux course : How to build a reaction web Applications

Reactive systems allow the unparalleled responsiveness and scalability we need in a high data flow world . However , Reactive systems require specially trained tools and developers to implement these unique program architectures .Spring WebFlux with Project Reactor It is a framework specially built to meet the reactivity needs of modern companies .

today , We're going to explain it WebFlux How to match with other reactive stack tools 、 How different and how to make the first application to help you get started WebFlux.

What is a reactive system ?

Reactive system is a system designed with reactive architecture pattern , This pattern takes precedence over loose coupling 、 Flexible and scalable components . They also designed fault solutions , To ensure that even if one system fails , Most systems still work .

Reactive systems focus on :

  • Reactivity : most important of all , Reactive systems should respond quickly to any user input . Proponents of reactive systems believe that , Reactivity helps optimize all other parts of the system , From data collection to user experience .
  • elastic : The reactive system shall be designed to predict system failure . Reactive systems expect components to eventually fail , And design loosely coupled systems , Even if several individual parts stop working , Can also remain active .
  • elastic : Reactive systems should be scaled up or down to meet requirements to adapt to the size of the workload . Many reactive systems will also use predictive scaling to predict and prepare for sudden changes . The key to achieving resilience is to eliminate any bottlenecks , Build systems that can split or copy components as needed .
  • Message driven communication : All the components of a reactive system are loosely coupled , There are hard boundaries between each component . Your system should communicate across these boundaries through explicit messaging . These messages make different components aware of the fault , And help them delegate the workflow to components that can handle it .

Reactions and other web The most significant difference between patterns is , Reactive systems can execute multiple unblocked calls at once , Instead of having some calls wait for others . therefore , Reactive systems can speed up performance and response , because web Each part of the application can complete its own part faster than waiting for another part .

In short , Reactive systems use loose coupling 、 Non blocking components to improve performance 、 User experience and error handling .

What is? Project Reactor

Project Reactor By Pivotal Framework built , from Spring powered . It realizes the reaction API Pattern , The most significant is the reactive flow specification .

If you are familiar with Java8 flow , You'll soon find streams and traffic ( Or its single element version Mono) There are many similarities between . The main difference between them is Flux and Monos Follow the publisher - Subscriber mode and implement back pressure , and StreamAPI There is no .

Back pressure is a signal from the data endpoint to the data producer , A way of indicating that it receives too much data . This allows better flow management and distribution , Because it prevents individual components from overworking .

Use Reactor The main advantage of is that you have complete control over the data flow . You can rely on the ability of subscribers to request more information when they are ready to process information , Or buffer some results on the publisher side , Even use the complete push method without back pressure .

In our reactive stack , It is located in Spring Boot 2.0 Lower and WebFlux above :

Spring WebFlux course : How to build a reaction web Applications

What is? Spring WebFlux?

Spring WebFlux Is a completely non blocking 、 Annotation based web frame , It is built on ProjectReactor On , Make in HTTP It is possible to build reactive applications on the layer .WebFlux Apply functional programming to... Using a new router functional feature web layer , And bypass declarative controllers and request mappings .WebFlux You are required to Reactor Import... As a core dependency .

WebFlux Is in Spring 5 Added in , As Spring MVC A passive alternative to , And added support for the following aspects :

  • Nonblocking thread : A concurrent thread that completes its specified task without waiting for the previous task to complete .
  • Reactive Stream API: A standardized tool , Includes asynchronous flow processing options and non blocking back pressure .
  • Asynchronous data processing : When data is processed in the background , Users can continue to use normal application functions without interruption .

Final ,WebFlux To cancel the SpringMVCs Per request thread model , But use multi-EventLoop Non blocking model to support reactive 、 Scalable applications . Because of the support Netty、Undertow and Servlet3.1+ Containers and other popular servers ,WebFlux Has become a key part of the reactive stack .

Spring WebFlux Significant characteristics of

Router function

RouterFunction It's a standard. SpringMVC Used in @RequestMapping and @Controller Functional alternatives to annotation styles .

We can use it to route requests to handler functions :

@RestControllerpublic class ProductController {    @RequestMapping("/product")    public List<Product> productListing() {        return ps.findAll();    }}

You can use RouterFunctions.route() Create route , Instead of writing complete router functions . Route is registered as Springbean, So you can create... In any configuration class .

The router function avoids the potential side effects caused by the multi-step process of request mapping , Instead, it's reduced to a direct router / Handler chain . This allows the functional programming implementation of reactive programming .

RequestMapping and Controller The annotation style is in WebFlux It still works , If you are more familiar with the old style ,RouterFunction It's just a new option for the solution .

WebClient

WebClient yes WebFlux The reaction of web client , By the famous RestTemplate structure . It's an interface , Express web The main entry point of the request , And supports synchronous and asynchronous operations .WebClient It is mainly used for reactive back-end to back-end communication .

You can use the Maven Import standards WebFlux Dependencies to build and create WebClient example :

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-webflux</artifactId></dependency>
WebClient client = WebClient.create();

Reactive Steam API

Reactive Steam API Is a collection of imported functions , Allow more intelligent streaming data streams . It has built-in support for back pressure and asynchronous processing , Ensure that applications make the most efficient use of computer and component resources .

Reaction flow API There are four main interfaces in :

1. Publisher: Send events to link subscribers according to their needs . Act as the central link point where subscribers can monitor events .

2. Subscriber: Receive and process events from the publisher . Multiple subscribers can link to a single publisher , And respond differently to the same event . Subscribers can be set to respond :

  • onNext, When it receives the next event .
  • onSubscribe, When adding a new subscriber
  • onError, When another subscriber has an error
  • onComplete, When another subscriber completes its task

3. Subscription: Define the relationship between the selected publisher and subscriber . Each subscriber can only link to one publisher .

4. Processor: Represents the processing phase of the subscriber

Servers

WebFlux stay Tomcat、Jetty、Servlet3.1+ Containers and Netty and Undertow Such as the Servlet Supported on runtime .Netty Most commonly used in asynchronous and non blocking designs , therefore WebFlux It will be used by default . Only need to Maven or Gradle Build software and make simple changes , You can easily switch between these Server Options .

This makes WebFlux It is highly versatile in terms of available technologies , And allows you to easily implement it in your existing infrastructure .

Concurrency model

WebFlux Non blocking is considered in the construction of , So we use the same as SpringMVC Different concurrent programming models .

SpringMVC Suppose the thread will be blocked , And use a large thread pool to keep moving during blocking instances . This larger thread pool makes MVC More resource intensive , Because the computer hardware must keep more threads running at the same time .

WebFlux Used a small thread pool , Because it assumes that you never need to work to avoid blocking . These threads are called event loop worker threads , It is fixed in quantity , Loop speed in incoming requests is faster than MVC Fast thread . It means WebFlux Computer resources can be used more effectively , Because the active thread is always working .

Spring WebFlux Security

WebFlux Use Spring Security Implement authentication and authorization protocols .Spring Security Use WebFilter Check the request against the list of authenticated users , It can also be set to automatically reject requests that meet conditions such as source or request type .

@EnableWebFluxSecuritypublic class HelloWebFluxSecurityConfig {    @Bean    public MapReactiveUserDetailsService userDetailsService() {        UserDetails user = User.withDefaultPasswordEncoder()            .username("user")            .password("user")            .roles("USER")            .build();        return new MapReactiveUserDetailsService(user);    }}

This is the smallest implementation that sets all settings to the default . ad locum , We can see that the user has a user name 、 One password and one or more role tags , Allow them a certain degree of access .

Start using SpringWebFlux

Now? , Let's experience WebFlux. First , We need to build a project . We will use SpringInitializer Generate a file with SpringReactiveWeb Dependent Maven structure .

Spring WebFlux course : How to build a reaction web Applications

This will generate a file like pom.xml

<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">    <modelVersion>4.0.0</modelVersion>    <parent>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-parent</artifactId>        <version>2.4.2</version>        <relativePath/> <!-- lookup parent from repository -->    </parent>    <groupId>com.example</groupId>    <artifactId>reactive-rest-service</artifactId>    <version>0.0.1-SNAPSHOT</version>    <name>reactive-rest-service</name>    <description>Demo project for Spring Boot</description>    <properties>        <java.version>1.8</java.version>    </properties>    <dependencies>        <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>        <dependency>            <groupId>io.projectreactor</groupId>            <artifactId>reactor-test</artifactId>            <scope>test</scope>        </dependency>    </dependencies>    <build>        <plugins>            <plugin>                <groupId>org.springframework.boot</groupId>                <artifactId>spring-boot-maven-plugin</artifactId>            </plugin>        </plugins>    </build></project>

Now you have everything you need to continue ! From here, we will add some components to make Hello World Applications . We will only add a router and a handler , This is the basis for creating WebFlux Minimum requirements for applications .

Router

First , We will create a sample router , stay URL Show text last time http://localhost:8080/example. This defines how the user requests the data we will define in the handler .

@Configurationpublic class ExampleRouter {  @Bean  public RouterFunction<ServerResponse> routeExample (ExampleHandler exampleHandler) {    return RouterFunctions        .route(RequestPredicates.GET("/example").and(RequestPredicates.accept(MediaType.TEXT_PLAIN)), exampleHandler::hello);  }}

Handler

Now? , We will add a handler , Used to listen for requests / Any user of the sample route . Once the router recognizes that the requested path matches , It sends the user to the handler . Our handler receives the message and takes the user to the page with our greeting .

@Componentpublic class ExampleHandler {  public Mono<ServerResponse> hello(ServerRequest request) {    return ServerResponse.ok().contentType(MediaType.TEXT_PLAIN)         .body(BodyInserters.fromObject("Hello, Spring WebFlux Example!"));  }}

Running the application

Now? , We will implement Maven command spring boot:run To run the application . You can now access http://localhost:8080/example Find... In the browser :

Hello, Spring WebFlux Example!

Original address :https://www.educative.io/blog/spring-webflux-tutorial

copyright notice
author[Old K's Java blog],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210825150422749Y.html

Random recommended