Spring Boot 2.0 WebFlux Getting Started Series: Quick Start (1)

02: WebFlux Quick Start Practice

Spring Boot 2.0

There is a striking sentence on the official website of spring.io:

BUILD ANYTHING WITH SPRING BOOT

The Spring Boot (Boot, as the name suggests, means boot) framework is used to simplify the process of Spring application from building to development. The application is ready to use out of the box, as long as you pass a command, including the command line java -jar, SpringApplicationapplication startup class, Spring Boot Maven plugin, etc., you can start the application. In addition, Spring Boot emphasizes that only few configuration files are required, so in the development of production-level Spring applications, development becomes more efficient and easier. Currently, the Spring Boot version is version 2.x. Spring Boot includes WebFlux.

image

Spring Boot 2.0 WebFlux

To understand WebFlux, first understand what is Reactive Streams. Reactive Streams is a stream-oriented library standard and specification in the JVM:

  • handle a potentially infinite number of elements
  • Process in order
  • Asynchronous transfer between components
  • Mandatory non-blocking backpressure

Backpressure

Backpressure is a common strategy that allows publishers to have unlimited buffer storage elements to ensure that publishers do not overwhelm subscribers if they publish elements too quickly.

Reactive Streams

Generally consists of the following:

  • Publisher: publishes elements to subscribers
  • Subscribers: consume elements
  • Subscriptions: In publishers, when a subscription is created, it will be shared with subscribers
  • Processor: Processes data between publishers and subscribers

Reactive programming With the standard and specification Reactive Streams, reactive programming can be done using the specification. Then understand what is Reactive programming. Reactive programming is based on asynchronous and event-driven non-blocking programs that scale vertically by launching a small number of threads within the JVM, rather than horizontally by clustering. This is a programming paradigm, how is it reflected in a specific project?

In the actual combat of responsive project programming, the framework Reactor based on the Reactive Streams specification is used to implement the actual combat. Reactor generally provides two reactive APIs:

  • Mono: implements the publisher, and returns 0 or 1 element
  • Flux: implements the publisher, and returns N elements

Spring Webflux

Spring Boot Webflux is based on Reactor. Spring Boot 2.0 includes a new spring-webflux module. This module contains support for reactive HTTP and WebSocket clients, as well as support for programs such as REST, HTML, and WebSocket interaction. Generally speaking, Spring MVC is used for synchronous processing and Spring Webflux is used for asynchronous processing.

Spring Boot Webflux has two programming model implementations, one is similar to Spring MVC annotations, and the other is using its functional endpoints. The annotations will be covered in the second article, and the following quick start is implemented in the functional way of Spring Webflux.

Spring Boot 2.0 WebFlux Features

Commonly used Spring Boot 2.0 WebFlux production features are as follows:

  • Reactive API
  • programming model
  • applicability
  • inline container
  • Starter component

There is also support for logging, web, messaging, testing, and extensions.

Reactive API

The Reactor framework is a dependency of the Spring Boot Webflux reactive library, through Reactive Streams and interacts with other reactive libraries. Two reactive APIs are provided: Mono and Flux. Generally, Publisher is used as input, converted to Reactor type within the framework and processed logic, and then returned Flux or Mono as output.

applicability

[Image upload failed...(image-3cb7cf-1523693503530)]

A picture is very clear, WebFlux and MVC have an intersection, which is convenient for everyone to migrate. But note:

  • If MVC can meet the scene, there is no need to change to WebFlux.
  • To pay attention to container support, see Support for inline containers below.
  • Microservice architecture, WebFlux and MVC can be mixed. Especially when developing IO-intensive services, choose WebFlux to implement.

programming model

The Spring 5 web module includes Spring WebFlux's HTTP abstraction. Similar to the Servlet API, WebFlux provides the WebHandler API to define a non-blocking API abstraction. You can choose between the following two programming model implementations:

  • Annotation control layer. Consistent with MVC, WebFlux also supports the reactive @RequestBody annotation.
  • Functional endpoint. A gadget for routing and processing requests based on the lambda lightweight programming model. The biggest difference from the above is that this model controls the entire request-response life process

inline container

Start the application like the Spring Boot framework, but WebFlux is started through Netty by default, and the default port is automatically set to 8080. Also provides support for containers such as Jetty, Undertow, etc. Developers can configure and use the corresponding embedded container instance by adding the corresponding container Starter component dependencies.

Note, however, that it must be a Servlet 3.1+ container, such as Tomcat, Jetty; or a non-Servlet container, such as Netty and Undertow.

Starter component

Like the Spring Boot framework, Spring Boot Webflux provides many "out of the box" Starter components. Starter components are Maven dependencies that can be loaded into an application. You only need to add the corresponding dependency configuration in the Maven configuration to use the corresponding Starter component. For example, adding spring-boot-starter-webfluxdependencies can be used to build reactive API services, including Web Flux and Tomcat embedded containers.

In development, many functions are implemented by adding Starter components. So, what are the commonly used Starter components in Spring Boot 2.x?

Spring Boot 2.0 WebFlux Components

Spring Boot WebFlux officially provides many Starter components, and each module will have a variety of technical implementation selection support to achieve various complex business requirements:

  • Web:Spring WebFlux
  • Template Engine: Thymeleaf
  • Storage: Redis, MongoDB, Cassandra. MySQL is not supported
  • Embedded containers: Tomcat, Jetty, Undertow

Quick start

Spring Initializr quickly builds the project skeleton

The Spring Boot Maven project is an ordinary Maven project, just add the corresponding Spring Boot dependencies. Spring Initializr is like a code generator, it automatically gives you a Spring Boot Maven project. Spring Initializr has two ways to get the Spring Boot Maven skeleton project:

start.spring.io online generation

Spring officially provides a website called Spring Initializr to guide you to quickly generate Spring Boot applications. The website address is: https://start.spring.io, and the operation steps are as follows:

The first step is to select the Maven or Gradle build tool, the development language Java, Kotlin or Groovy, and finally determine the Spring Boot version number. The Maven build tool, Java development language and Spring Boot 2.0.1 are selected by default here.

The second step, enter the Maven project information, that is, the project group groupIdand name artifactId. The corresponding Maven information here is:

  • groupId:springboot
  • artifactId: sspringboot-webflux-1-quickstart The default version here is 0.0.1-SNAPSHOT. Three properties are uniquely identified in the Maven dependency repository.

The third step is to select the Starter components and other dependencies required by the project. Finally, click the Generate button to get the skeleton project compressed package. Here is a quick start, just choose Reactive Web. As shown in Figure 1-8.

[Image upload failed...(image-786839-1523693503530)]

Configure POM dependencies

Check whether the spring-boot-starter-webflux dependency is configured in the project POM file. If it is automatically generated above, the configuration is as follows:

  <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>

The spring-boot-starter-webflux dependency is the core package we need to learn about webflux, which includes the spring-boot-starter-reactor-netty and spring 5 webflux packages by default. That is to say, the default is to start through netty.

The two dependencies of reactor-test and spring-boot-starter-test are used for unit testing.

spring-boot-maven-plugin is a Spring Boot Maven plugin that can be invoked for running, compiling, etc.

Write the handler class Handler

Create a new package org.spring.springboot.handler as a function handling class. The processing class CityHandler of the new city (City) example, the code is as follows:

import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

@Component
public class CityHandler {

    public Mono<ServerResponse> helloCity(ServerRequest request) {
        return ServerResponse.ok().contentType(MediaType.TEXT_PLAIN)
                .body(BodyInserters.fromObject("Hello, City!"));
    }
}

ServerResponse is the encapsulation of the response, which can set the response status, response header, and response body. For example, ok represents the 200 response code, the MediaType enumeration represents the text content type, and the returned object is a String.

Mono is used here as the return object because the return contains a ServerResponse object instead of multiple elements.

Write the router class Router

Create a new org.spring.springboot.router package as a router class. The routing class CityRouter of the new City example, the code is as follows:

import org.spring.springboot.handler.CityHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;

@Configuration
public class CityRouter {


    @Bean
    public RouterFunction<ServerResponse> routeCity(CityHandler cityHandler) {
        return RouterFunctions
                .route(RequestPredicates.GET("/hello")
                                .and(RequestPredicates.accept(MediaType.TEXT_PLAIN)),
                        cityHandler::helloCity);
    }

}

RouterFunctions is a class for request routing processing, that is, routing requests to processors. Here a GET request /hello is routed to the helloCity method of the handler cityHandler. Similar to HandleMapping in Spring MVC mode.

For the RouterFunctions.route(RequestPredicate, HandlerFunction) method, the corresponding input parameters are the request parameters and the handler function. If the request matches, the corresponding handler function is called.

A simple service has been written here. How to run the service below.

Start the running project

A simple Spring Boot Webflux project has been developed. Let's run the project to verify it. Use the IDEA right toolbar, click the Maven Project Tab, and click the installcommand to . Or use the command line form, in the project root directory, execute Maven to clean and install the project command:

cd springboot-webflux-1-quickstart
mvn clean install

See the successful output in the console:

... 省略
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:30 min
[INFO] Finished at: 2017-10-15T10:00:54+08:00
[INFO] Final Memory: 31M/174M
[INFO] ------------------------------------------------------------------------

Run the project

Execute Applicationclass normal mode or in Debug mode. The output of a successful run can be seen in the console:

... 省略
2018-04-10 08:43:39.932  INFO 2052 --- [ctor-http-nio-1] r.ipc.netty.tcp.BlockingNettyContext     : Started HttpServer on /0:0:0:0:0:0:0:0:8080
2018-04-10 08:43:39.935  INFO 2052 --- [           main] o.s.b.web.embedded.netty.NettyWebServer  : Netty started on port(s): 8080
2018-04-10 08:43:39.960  INFO 2052 --- [           main] org.spring.springboot.Application        : Started Application in 6.547 seconds (JVM running for 9.851)

At first glance, it is indeed Netty started.

Open the browser, visit the /hello address, and you will see the return result as shown in the figure:

[Image upload failed...(image-80ce85-1523693503530)]

finally

Development runtime environment:

  • JDK 1.8+ Spring Boot 2.x requires JDK 1.8 environment and above. In addition, Spring Boot 2.x is only compatible with Spring Framework 5.0 and above.

  • Maven 3.2+ provides related dependencies for Spring Boot 2.x. The build tool is Maven, which requires version 3.2 and above. Using Gradle requires version 1.12 and above. Maven and Gradle, you can choose your favorite.

  • IntelliJ IDEA IntelliJ IDEA (IDEA for short) is a commonly used development tool and is recommended in this book. It is also possible to use the Eclipse IDE as well.

Development and use framework:

  • Mongodb
  • Redis
  • Thymeleaf
  • WebSocket

Course Catalog

  • "01: Course Outline"
  • "02: WebFlux Quick Start Practice"
  • "03: WebFlux Web CRUD Practice"
  • "04: WebFlux integrates Mongodb"
  • "05: WebFlux Integration with Thymeleaf"
  • "06: Thymeleaf and Mongodb Practice in WebFlux"
  • "07: WebFlux integrates Redis"
  • "08: Redis Implementation Cache in WebFlux"
  • "09: WebSocket Communication in WebFlux"
  • "10: WebFlux Integration Testing and Deployment"
  • "11: WebFlux Actual Book Management System"

Course Series: Portal Course Series: Portal Course Series : Portal

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324434696&siteId=291194637