Springboot2 Learning-webflux1__web

Source: Internet
Author: User
Introduced in spring Boot2 Webflux, first understand some of the webflux concepts and features, Spring Boot 2.0 Webflux, then what is reactive Streams.

Reactive STREAMS is a stream-oriented library standard and specification in the JVM: handling potentially unlimited numbers of elements
Processed sequentially
Asynchronous delivery between components
Mandatory non-blocking back pressure (backpressure)


Backpressure (back pressure): Back pressure is a common strategy that allows publishers to have unlimited buffer storage elements to ensure that publishers are publishing elements too fast to suppress subscribers. Reactive STREAMS (Response stream)
Generally consists of the following:
Publisher: Publish elements to Subscribers
Subscribers: Consumer Elements
Subscription: In the publisher, when a subscription is created, it is shared with the subscriber
Processor: Process data between publishers and Subscribers
Responsive programming


With the reactive STREAMS Standard and specification, the specification can be used for responsive programming. Then understand what is reactive programming responsive programming. Responsive programming is based on asynchronous and event-driven non-blocking programs, but only vertically by starting a small number of thread extensions within the JVM, rather than horizontally through the cluster extension. This is a programming paradigm, and how does it work in a specific project?


Responsive project programming in combat, through the framework based on the reactive STREAMS specification Reactor to combat. Reactor generally provides two types of responsive APIs:

Mono: Implementing a Publisher and returning 0 or 1 elements
Flux: Implements the publisher and returns N elements
Spring Webflux


Spring Boot Webflux is implemented based on Reactor. Spring Boot 2.0 includes a new Spring-webflux module. The module contains support for responsive HTTP and WebSocket clients, as well as for programs such as rest,html and WebSocket interactions. In general, Spring MVC is used for synchronous processing, and spring Webflux is used for asynchronous processing.

Spring Boot Webflux has two programming model implementations, one similar to the Spring MVC annotation and the other using its functional endpoint approach. The annotations are implemented in the following QuickStart with the Spring webflux functional approach.


Spring Boot 2.0 Webflux Features

The typical Spring Boot 2.0 Webflux production features are as follows:
Responsive API
Programming model
Applicability
Inline container
Starter components
There are also support for logs, WEB, messaging, testing, and extensions.


Responsive API:

The Reactor framework is a Spring Boot Webflux response Library dependency, reactive Streams and interacting with other response libraries. Two types of reactive api:mono and Flux are provided. Publisher is generally used as input, converted into a Reactor type within the framework and processed, and then returned by Flux or Mono as the output.


Applicability:

If MVC satisfies the scene, it does not need to be changed to Webflux.
To be aware of the container support, you can look at the following inline container support.
MicroServices architectures, Webflux and MVC can be mixed. Especially when developing IO-intensive services, choose Webflux to implement.


Programming Model:
The Spring 5 Web module contains the HTTP abstraction for spring Webflux. Like the Servlet API, Webflux provides the WebHandler API to define a non-blocking API abstraction interface. You can choose from the following two programming model implementations:
Annotate the control layer. Consistent with MVC, Webflux also supports responsive @RequestBody annotations.

Functional Endpoints. A small tool for routing and processing requests based on the lambda lightweight programming model. And the biggest difference is that this model, the whole process of controlling the request-response life Flow


Inline container:
Launches the app just like the Spring boot framework, but Webflux starts with Netty by default and automatically sets the default port to 8080. Support is also provided for containers such as Jetty, Undertow and so on. The developer can configure and use the corresponding inline container instance by adding the corresponding container Starter component dependencies on its own.
Note, however, that it must be a servlet 3.1+ container, such as Tomcat, Jetty, or non-servlet containers, such as Netty and Undertow.

Starter components:
Like the spring boot framework, Spring boot Webflux provides many Starter components that are "out of the box." The Starter component is a Maven dependency that can be loaded in the app. You only need to add the corresponding dependency configuration in the Maven configuration to use the corresponding Starter component. For example, adding a spring-boot-starter-webflux dependency can be used to build a responsive API service that includes Web Flux and Tomcat inline containers.


In development, many of the features are implemented by adding Starter components. So what are the common Starter components of the Spring Boot 2.x?
Spring Boot 2.0 Webflux components:
Spring Boot Webflux officially offers a number of Starter components, each of which has a variety of technologies for selecting support to achieve complex business requirements:
Web:spring Webflux
Template engine: Thymeleaf
Storage: Redis, MongoDB, Cassandra, MySQL not supported
Inline containers: Tomcat, Jetty, Undertow


These are some of the concepts below, starting with Webflux's Hello World Mini Demo:

One, create Webflux project

For idea, create a spring boot project that introduces the Spring-boot-starter-webflux package, as shown in the following illustration:



Pom.xml inside the configuration is as follows:

<?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/http Maven.apache.org/xsd/maven-4.0.0.xsd "> <modelVersion>4.0.0</modelVersion> <groupid>com.jack </groupId> <artifactId>webflux1</artifactId> <version>0.0.1-SNAPSHOT</version> < Packaging>jar</packaging> <name>webflux1</name> <description>demo Project for Spring Boot </description> <parent> <groupId>org.springframework.boot</groupId> <artifactId> Spring-boot-starter-parent</artifactid> <version>2.0.1.RELEASE</version> <relativePath/> <!--lookup parent from repository--</parent> <properties> <project.build.sourceencoding>u Tf-8</project.build.sourceencoding> <project.reporting.outputencoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties > <dependencies> <dependency> <groupId>org.springframework.boot</groupId> &LT;ARTIFAC tid>spring-boot-starter-webflux</artifactid> </dependency> <dependency> <groupid>org.s Pringframework.boot</groupid> <artifactId>spring-boot-starter-test</artifactId> <scope> test</scope> </dependency> <dependency> <groupId>io.projectreactor</groupId> <a rtifactid>reactor-test</artifactid> <scope>test</scope> </dependency> </ dependencies> <build> <plugins> <plugin> <groupid>org.springframework.boot</group id> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build
 > </project>

Spring-boot-starter-webflux dependence, is our core need to learn Webflux package, which contains the Spring-boot-starter-reactor-netty, Spring 5 Webflux package, This means that the default is initiated via Netty.
Reactor-test, spring-boot-starter-test Two dependencies are used for unit testing.
Spring-boot-maven-plugin is a Spring boot maven plugin that can be run, compiled, and so on.

After the successful creation, the output of the successful startup is as follows:

  . ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | ||  (_| | ) ) ) )
  '  |____| .__|_| |_|_| |_\__, |  ////=========|_|==============|___/=/_/_/_/:: Spring Boot:: (v2.0.1.release) 2018-04-21 22:25:25.294 INFO 16920---[main] com.jack.webflux1.Webflux1Application:Starting webflux1application on WJ with PID 16920 (E:\webworkspace\IdeaProjects\springcloud4\webflux1\target\classes started by Administrator in E:\webworkspace\     IDEAPROJECTS\SPRINGCLOUD4) 2018-04-21 22:25:25.299 INFO 16920---[main] com.jack.webflux1.Webflux1Application           : No Active profile set, falling back to default Profiles:default 2018-04-21 22:25:25.342 INFO 16920---[ Main] Onfigreactivewebserverapplicationcontext:refreshing org.springframework.boot.web.reactive.context.annotationconfigreactivewebserverapplicationcontext@1198b989: startup Date [Sat APR 21 22:25:25 gmt+08:00 2018]; Root of context hierarchy 2018-04-21 22:25:26.354 INFO 16920---[main] o.s.w.r.handler.simpleurlhandlermappin g:mapped URL Path [/webjars/**] onto handler of type [class Org.springframework.web.reactive.resource.ResourceWebHandle R] 2018-04-21 22:25:26.354 INFO 16920---[main] o.s.w.r.handler.simpleurlhandlermapping:mapped URL path [/  * *] onto handler of type [Class Org.springframework.web.reactive.resource.ResourceWebHandler] 2018-04-21 22:25:26.425 INFO 16920---[main] o.s.w.r.r.m.a.controllermethodresolver:looking for @ControllerAdvice: org.springframe Work.boot.web.reactive.context.annotationconfigreactivewebserverapplicationcontext@1198b989:startup Date [Sat APR 22:25:25 gmt+08:00 2018];        Root of context hierarchy 2018-04-21 22:25:26.756 INFO 16920---[main] o.s.j.e.a.annotationmbeanexporter : Registering beans for JMX exposure on startup 2018-04-21 22:25:27.272 INFO 16920---[ctor-http-nio-1] r.ipc.netty.tcp.blockingnettycontext:started httpserver on/0:0:0:0:0:0:0:0:8080 2018-04-21 22:25:27.272 INFO 1692  0---[main] o.s.b.web.embedded.netty.nettywebserver:netty started on port (s): 8080 2018-04-21 22:25:27.275  INFO 16920---[main] com.jack.webflux1.Webflux1Application:Started webflux1application in 2.324

Look at the output, you can see, by default, using Netty as a container to start, the default port is 8080


Two, code writing

1, write processor class handler

Package Com.jack.webflux1.handler;

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;

/**
 * Create by Jack 2018/4/21 */
@Component Public
class HelloWorldHandler {
    /**
     * Serverresponse is the encapsulation of the response, which can set the response status, the response header, and the response body.
     * For example, OK represents the 200 response code, the mediatype enumeration is the object that represents the text content type, and the String is returned.
     here, Mono is used as the return object because the return contains a Serverresponse object instead of multiple elements
     * @param request
     * @return
     */Public
    Mono<serverresponse> HelloWorld (serverrequest request) {
        return Serverresponse.ok (). ContentType ( Mediatype.text_plain)
                . Body (Bodyinserters.fromobject ("Hello, World flux!");}
}
2, write router

2, writing router routers

Package com.jack.webflux1.router;
Import Com.jack.webflux1.handler.HelloWorldHandler;
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;  /** * Create by Jack 2018/4/21 * Configure routing */@Configuration public class Helloworldrouter {/** * routerfunctions For the request route processing class, the request is routed to the processor, where a GET request/helloworld is routed to the processor * Cityhandler Hellocity method.
     Similar to the handlemapping in Spring MVC mode.
     Routerfunctions.route (Requestpredicate, Handlerfunction) method, the corresponding entry parameter is the request parameter and the handler function, if the request matches, the corresponding processor function is called. * @param helloworldhandler * @return * */@Bean public routerfunction<serverresponse> Routehelloworld (HelloWorldHandler helloworldhandler) {return routerfunctions. Route (REQUESTP Redicates.
                        GET ("/helloworld"). and (Requestpredicates.accept (Mediatype.text_plain)),
    Helloworldhandler::helloworld);
 }
}


The above code is written, the request, the return Hello, World flux!


Three, test

Launch the app, test with postman, URL: Http://localhost:8080/helloWorld


The results of the return are shown below:



Source Address: Https://github.com/wj903829182/springcloud5/tree/master/webflux1

Source of study Reference: http://gitbook.cn/gitchat/column/5acda6f6d7966c5ae1086f2b/topic/5acda9d9d7966c5ae1087053

Welcome Dabigatran: 331227121, learn to communicate together

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.