Spring Boot WebFlux tutorial to get started

Spring Boot WebFlux tutorial to get started

 

background

As we all know, Spring Framework is a Java / Spring cross-platform application development framework, is also a Java EE (Java Enterprise Edition) lightweight framework that Spring provides a comprehensive platform infrastructure support for Java developers, although the basic components of Spring Code is lightweight, but its configuration is still a heavyweight.

That is how to solve it? Of course Spring Boot, Spring Boot provides a new programming model that allows the development of Spring applications become more simple and convenient. This course will be starting from the best practices of each project, involving the development of all aspects related to Spring Boot, the following first understand Spring Boot framework.

What is Spring Boot

Spring Boot (Boot name suggests, is to guide means) from the building framework to simplify the development process Spring applications. Application of a box, simply by a command, including a command line java -jar, SpringApplication application startup classes, Spring Boot Maven plug etc., the application can be started. In addition, Spring Boot emphasized requires very little configuration file, so in the development and production stage Spring applications, allowing developers to become more efficient and simple. Currently, Spring Boot version 2.x version.

What is Spring Boot WebFlux

You can see the above chart, WebFlux as important as the relative MVC. Most scenes are blocked using MVC style, WebFlux use scenario is asynchronous non-blocking, what is reactive programming (Reactive Programming)?

The official described the document: reactive programming is based on the non-blocking asynchronous and event-driven program, only a small amount of vertical threads started by expansion in the JVM, rather than horizontally through the cluster expansion.

Spring Boot 2.0 comprises a spring-webflux new module, the module comprising a support and responsive WebSocket HTTP client, and support for REST, HTML, and the like WebSocket interactive program.

Why learn Spring Boot WebFlux

  • Micro-service architecture more and more fire, Spring Boot is a big trend, because Spring Cloud is based on Spring Boot, so learn Spring Boot WebFlux will benefit.
  • From a programming is concerned, although blocking programming is unavoidable, but Reactive programming in most scenarios, can improve resource utilization. So, learning WebFlux, in particular, some very IO intensive scene just to be.

What can be learned in this course

This course is a basic tutorial series, the goal is to lead the reader to use combat, a new version of the Spring core curriculum concepts Boot 2.0 WebFlux as the main line. Series of tutorials around Spring Boot 2.0 WebFlux technology stack, the goal is to lead the reader to understand Spring Boot 2.0 WebFlux various characteristics, and learn to use Spring Boot related technology stack to use development projects. Especially for the next micro-services, if the IO-intensive and other scenes, you can consider using WebFlux to achieve.

The main points included knowledge: Getting Started, CRUD, MongoDB Reactive, Thymeleaf, Redis, WebSocket and so on, step by step way to understand the use of each component, the last comprehensive exercise.

After careful study completed this series of articles, Spring Boot 2.0 WebFlux will have a better understanding, have started using Spring Boot 2.0 WebFlux basic capacity development.

I earlier wrote the article can see my  GitHub .

Suitable for reading the crowd

This course is suitable for the following GitChat crowd read:

  • Spring Boot 2.0 WebFlux new version of novice staff
  • For developers interested in the development of Spring Boot 2.0 WebFlux
  • I want to know Spring Boot 2.0 WebFlux R & D personnel

Spring Boot 2.0.1.RELEASE version demo versions of development, technical personnel need to have Maven, Git basic skills.

Development operating environment:

  • JDK 1.8 + Spring Boot 2.x environment requires JDK 1.8 or later. In addition, Spring Boot 2.x compatible only with Spring Framework 5.0 and above.
  • Maven 3.2+ provides for the relevant dependent Spring Boot 2.x build tool is Maven, the version 3.2 and above, you will need to use Gradle 1.12 and above. Maven and Gradle each pick at like just fine.
  • IntelliJ IDEA IntelliJ IDEA (referred to as IDEA) is commonly used development tools, this book is recommended, also using the Eclipse IDE is naturally possible.

Use development framework:

  • MongoDB
  • Redis
  • Thymeleaf
  • WebSocket

Course Catalog

  • "Introduction: Course Outline"
  • "Lesson 01: WebFlux Quick Start Practice"
  • "The first lesson 02: WebFlux Web CRUD practice"
  • "Lesson 03: WebFlux integrate MongoDB"
  • "Of course: WebFlux integration Thymeleaf"
  • "The first 05 Lesson: WebFlux in Thymeleaf and MongoDB practice"
  • "The first 06 Lesson: WebFlux integrate Redis"
  • "Lesson 07: WebFlux in Redis implement caching"
  • "Lesson 08: WebFlux in WebSocket communicate"
  • "Lesson 09: WebFlux integration testing and deployment."
  • "Lesson 10: WebFlux actual library management system"

Lesson 01: WebFlux Quick Start Practice

Spring Boot 2.0

spring.io official website saying the words are striking:

BUILD ANYTHING WITH SPRING BOOT

Spring Boot (Boot name suggests, is to guide means) from the building framework to simplify the development process Spring applications. Application of a box, simply by a command, including a command line  java -jar , SpringApplication the application start type, Spring Boot Maven plug etc., the application can be started. In addition, Spring Boot emphasized requires very little configuration file, so in the development and production stage Spring applications, allowing developers to become more efficient and simple. Currently, Spring Boot version 2.x version. Spring Boot include WebFlux.

Spring Boot 2.0 WebFlux

Learn WebFlux, at first understand what is Reactive Streams. Reactive Streams the JVM library is stream oriented standards and specifications:

  • Deal with a potentially infinite number of elements
  • Order processing
  • Asynchronous transfer between components
  • Non-blocking mandatory backpressure (Backpressure)

Backpressure (back pressure)

Back pressure is a common strategy, so that the publisher has unlimited buffer storage elements, used to ensure that publishers release element too fast, not to suppress subscribers.

Reactive Streams (responsive flow)

Generally consists of:

  • Publishers: elements to subscribers
  • Subscribers: Consumer element
  • Subscriptions: In Publisher, a subscription is created, will be shared with subscribers
  • Processor: processing data between publishers and subscribers

Reactive programming

With Reactive Streams such standards and norms by specification can be reactive programming. That case then understand what is Reactive programming reactive programming. Reactive programming is based on the non-blocking asynchronous and event-driven program, only a small amount of vertical threads started by expansion in the JVM, rather than horizontally through the cluster expansion. This is a programming paradigm, how specific projects embody it?

Responsive actual programming project by the frame Reactor Based Reactive Streams specification implemented to combat. Reactor responsive offers two general API:

  • Mono: to achieve the publisher, and returns 0 or 1 element
  • Flux: to achieve the publisher, and return N elements

Spring Webflux

Spring Boot Webflux based Reactor is achieved. Spring Boot 2.0 comprises a spring-webflux new module. The module comprises a support and responsive WebSocket HTTP client, and support for REST, HTML, and the like WebSocket interactive program. Generally, Spring MVC for synchronization, Spring Webflux for asynchronous processing.

Spring Boot Webflux There are two programming models to achieve a similar manner Spring MVC annotations, and the other is to use its functional endpoints way. The notes will be mentioned in the second article, the following QuickStart implemented in Spring Webflux functional way.

Spring Boot 2.0 WebFlux properties

Spring Boot 2.0 WebFlux common production characteristics are as follows:

  • Responsive API
  • Programming Model
  • applicability
  • Embedded container
  • Starter assembly

As well as support for logging, Web, messaging, testing and expansion.

Responsive API

Reactor Spring Boot Webflux response frame is dependent library by Reactive Streams respond and interact with other libraries. It provides two responsive API: Mono and Flux. The Publisher is typically used as an input, the conversion into Reactor type inside the frame processing logic and then returns as an output Flux or Mono.

applicability

file

A map is very clear, WebFlux and MVC intersect, facilitate migration. But be careful:

  • MVC to meet the scene, there is no need to change WebFlux.
  • Pay attention to support the container, you can see the following support inline container.
  • Micro-service architecture, WebFlux and MVC can be mixed. In particular, the development of IO-intensive services, the choice WebFlux to achieve.

Programming Model

Spring 5 web module contains abstract Spring WebFlux of HTTP. Similarly Servlet API, WebFlux WebHandler API provides a non-blocking API to define the abstract interface. You can choose from the following two programming models to achieve:

  • Notes control layer. MVC and consistent, WebFlux also supports responsive @RequestBody comment.
  • Functional endpoints. lambda weight programming model for routing and processing requests gadgets. And above the biggest difference is that this model, full control of the request - response life processes

Embedded container

Boot with the Spring framework of the same launch applications, but WebFlux default by Netty start, and automatically sets the default port 8080. It also provides support for Jetty, Undertow and other containers. Self developer container Starter adding the corresponding component depends, to configure and use the corresponding embedded container instance.

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

Starter assembly

Like Spring framework of Boot, Spring Boot Webflux provide a lot of "out of the box," the Starter components. Starter assembly that may be loaded in the application Maven dependency. Just add in the corresponding configuration-dependent Maven configuration corresponding to use Starter assembly. For example, adding  spring-boot-starter-webflux dependency, it can be used to construct responsive API service, which includes the embedded Web Flux Tomcat containers and the like.

Development, many functions are to be achieved by adding Starter component of the way. Well, Spring Boot 2.x Starter commonly used components, what does?

Spring Boot 2.0 WebFlux assembly

Spring Boot WebFlux official Starter many components, each module will support a variety of technology selection, to achieve a variety of complex business needs:

  • Web:Spring WebFlux
  • Template engine: Thymeleaf
  • Storage: Redis, MongoDB, Cassandra, MySQL does not support
  • Embedded containers: Tomcat, Jetty, Undertow

Spring Initializr quickly build project skeleton

Spring Boot Maven project, Maven is an ordinary project, joined the corresponding Spring Boot can rely on. Spring Initializr is the same as the code generator, you automatically give out a Spring Boot Maven project. Spring Initializr There are two ways to get a skeleton Spring Boot Maven project:

start.spring.io generated online

Spring provides the official website called Spring Initializr, and to guide you quickly generate Spring Boot application. Web site address, see here , follow these steps:

The first step, Gradle or Maven build tool selection, development language Java, Kotlin or Groovy, Spring Boot finalized version number. Here is selected by default Maven build tool, Java programming language and Spring Boot 2.1.5.

The second step, enter the Maven project information, ie project team groupId and name artifactId, where the corresponding Maven information:

  • groupId:springboot
  • artifactId:sspringboot-webflux-1-quickstart

Here is the default version number version 0.0.1-SNAPSHOT, three properties depend warehouse in Maven is uniquely identified.

The third step, select the required engineering Starter components and other dependencies, and finally click "Generate" button, you can get a skeleton project archive, quick start here, simply select the Reactive Web can, as shown.

POM dependent on configuration

Check the project POM file, whether or not equipped with spring-boot-starter-webflux dependence. If it is automatically generated above 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>

spring-boot-starter-webflux dependent, we need to learn webflux core packages, which by default includes spring-boot-starter-reactor-netty, spring 5 webflux package, that is by default netty started.

reactor-test, spring-boot-starter-test for two means with dependent testing.

spring-boot-maven-plugin is Spring Boot Maven plug-ins, you can run the compiler and other calls.

Write processor class Handler

New Package org.spring.springboot.handler, as a function of write processing class. New City (City) treatment class example CityHandler, 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;@Componentpublic class CityHandler {    public Mono<ServerResponse> helloCity(ServerRequest request) {        return ServerResponse.ok().contentType(MediaType.TEXT_PLAIN)                .body(BodyInserters.fromObject("Hello, City!"));    }}

ServerResponse encapsulation response is to be provided in response to the state, the first response, the response body. For example, ok represents the 200 response code, MediaType enumeration is a representative of this text type, returns a String object.

As used herein Mono returned object, because the object returned contains a ServerResponse, rather than a plurality of elements.

Writing class router Router

New org.spring.springboot.router package, as written in the router category. New City (City) Routing example CityRouter, 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;@Configurationpublic class CityRouter {    @Bean    public RouterFunction<ServerResponse> routeCity(CityHandler cityHandler) {        return RouterFunctions                .route(RequestPredicates.GET("/hello")                                .and(RequestPredicates.accept(MediaType.TEXT_PLAIN)),                        cityHandler::helloCity);    }}

RouterFunctions routing processing based on the request, i.e. requests are routed to the processor, where the request is a GET / hello helloCity routed to the processor-cityHandler. Similarly with HandleMapping role in Spring MVC pattern.

RouterFunctions.route (RequestPredicate, HandlerFunction) method, the corresponding request parameters and the parameters are a function of the processing, if the request matches, call processor function corresponding.

Here a simple service was written, how to run the service below.

Project up and running

A simple Spring Boot Webflux on completion of the development project, and run the project under the following verification. IDEA using the right side of the toolbar, click the Maven Project Tab, click the Maven plugin using the following command to install or use the command line of the form, in the project root directory, execute instructions Maven clean-up and installation of:

cd springboot-webflux-1-quickstartmvn clean install

See the success of the 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

Application execution classes start in IDEA, any normal mode or Debug mode, you can see the output of a successful run 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:80802018-04-10 08:43:39.935  INFO 2052 --- [           main] o.s.b.web.embedded.netty.NettyWebServer  : Netty started on port(s): 80802018-04-10 08:43:39.960  INFO 2052 --- [           main] org.spring.springboot.Application        : Started Application in 6.547 seconds (JVM running for 9.851)

A look, really Netty started.

Open your browser and visit / hello address, you will see the return results as shown:

file

to sum up

This paper stresses Spring Boot 2.0 WebFlux background and use quick start with is based on the functional endpoint to create a service, but this code is a little above normal. A CRUD next lesson we are using annotation layer that allows developers more convenient.

Guess you like

Origin blog.csdn.net/zhangbijun1230/article/details/91353764