SpringBoot2 using Webflux Functional programming

Source: Internet
Author: User

This article simply uses SpringBoot2 to use Webflux's functional programming, and will continue to write about Webflux related articles.

Recently has been studying Webflux, follow-up will be a number of related articles in succession.

First look at a picture of the srping official online, compare SPRINGMVC and Spring Webflux,

Check out the official documentation for Webflux: https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html# Spring-webflux,webflux provides functional programming, this article briefly introduces Webflux functional programming simple use.

New Project

To create a project, the Pom file introduces Webflux dependencies, and the complete pom file 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.dalaoyang</ Groupid> <artifactId>springboot2_webflux</artifactId> <version>0.0.1-snapshot</version > <packaging>jar</packaging> <name>springboot2_webflux</name> <description>sprin        Gboot2_webflux</description> <parent> <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.3.RELEASE</version> <relativePath/> <!--lookup parent from repository to </parent> <properties> <p Roject.build.sourceencoding>utf-8</projecT.build.sourceencoding> <project.reporting.outputencoding>utf-8</project.reporting.outputencoding > <java.version>1.8</java.version> </properties> <dependencies> <depende Ncy> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-starte r</artifactid> </dependency> <dependency> <groupid>org.springframework.bo Ot</groupid> <artifactId>spring-boot-starter-test</artifactId> &LT;SCOPE&GT;TEST&L t;/scope> </dependency> <dependency> <groupid>org.springframework.boot</g roupid> <artifactId>spring-boot-starter-webflux</artifactId> </dependency> </ dependencies> <build> <plugins> <plugin> <groupid>org.sprin Gframework.boot</groupid> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </b Uild></project>

First try to introduce Webflux dependency, whether the SPRINGMVC mode can still use, create a new Hellocontroller, complete code as follows, after the implementation of the discovery, is able to perform normal access, which is actually what we call the annotated programming.

package com.dalaoyang.controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;/** * @author dalaoyang * @project springboot_learn * @package com.dalaoyang.controller * @email [email protected] * @date 2018/7/30 */@RestControllerpublic class HelloController {    @GetMapping("hello")    public String Hello(){        return "Hello this is SpringWebFlux";    }}

Results

Next use functional programming, first look at the official documents,

We need to create a handlerfunction return value of Mono, create a new Hihandler, write a method hi, complete the code as follows:

package com.dalaoyang.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;/** * @author dalaoyang * @project springboot_learn * @package com.dalaoyang.handler * @email [email protected] * @date 2018/7/30 */@Componentpublic class HiHandler {    public Mono<ServerResponse> Hi(ServerRequest request) {        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)                .body(BodyInserters.fromObject("Hi , this is SpringWebFlux"));    }}

Where Serverresponse is the corresponding package object, the following is its source code, which contains the response status, the response header, and so on, as follows:

Package Org.springframework.web.reactive.function.server;import Java.net.uri;import Java.time.ZonedDateTime; Import Java.util.list;import java.util.map;import Java.util.set;import Java.util.function.bifunction;import Java.util.function.consumer;import Org.reactivestreams.publisher;import Org.springframework.core.parameterizedtypereference;import Org.springframework.http.cachecontrol;import Org.springframework.http.httpheaders;import Org.springframework.http.httpmethod;import Org.springframework.http.httpstatus;import Org.springframework.http.mediatype;import Org.springframework.http.responsecookie;import Org.springframework.http.codec.httpmessagewriter;import Org.springframework.http.server.reactive.serverhttpresponse;import Org.springframework.util.MultiValueMap; Import Org.springframework.web.reactive.function.bodyinserter;import Org.springframework.web.reactive.result.view.viewresolver;import Org.springframework.web.server.serverwebexchange;import Reactor.core.publisher.mono;public inTerface serverresponse {httpstatus statusCode ();    Httpheaders headers ();    Multivaluemap<string, responsecookie> cookies ();    Mono<void> WriteTo (Serverwebexchange var1, Serverresponse.context var2);    Static Serverresponse.bodybuilder from (Serverresponse other) {return new Defaultserverresponsebuilder (other);     } Static Serverresponse.bodybuilder status (Httpstatus status) {return new Defaultserverresponsebuilder (status);    } static Serverresponse.bodybuilder status (int status) {return new Defaultserverresponsebuilder (status);    } static Serverresponse.bodybuilder ok () {return status (Httpstatus.ok); } static Serverresponse.bodybuilder created (URI location) {Serverresponse.bodybuilder builder = status (Httpstat us.        CREATED);    Return (Serverresponse.bodybuilder) builder.location (location);    } static Serverresponse.bodybuilder accepted () {return status (httpstatus.accepted); } Static ServerreSponse.    Headersbuilder<?> nocontent () {return status (httpstatus.no_content); } static Serverresponse.bodybuilder Seeother (URI location) {Serverresponse.bodybuilder builder = status (Httpsta Tus.        See_other);    Return (Serverresponse.bodybuilder) builder.location (location); } static Serverresponse.bodybuilder Temporaryredirect (URI location) {Serverresponse.bodybuilder Builder = Statu        S (httpstatus.temporary_redirect);    Return (Serverresponse.bodybuilder) builder.location (location); } static Serverresponse.bodybuilder Permanentredirect (URI location) {Serverresponse.bodybuilder Builder = Statu        S (httpstatus.permanent_redirect);    Return (Serverresponse.bodybuilder) builder.location (location);    } static Serverresponse.bodybuilder Badrequest () {return status (Httpstatus.bad_request);    } static serverresponse.headersbuilder<?> NotFound () {return status (Httpstatus.not_found); } Static ServerresponSe.    Bodybuilder unprocessableentity () {return status (httpstatus.unprocessable_entity);        } public interface Context {list

Looking back at the image of the official document above, you also need to configure a route similar to the @requestmapping function, via Routerfunctions.route (Requestpredicate, handlerfunction) Provides a default implementation of a router function, creating a new Hirouter with the following code:

Package Com.dalaoyang.router;import Com.dalaoyang.handler.hihandler;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;/** * @author Dalaoyang * @project Springboot_learn * @package com.dalaoyang.router * @email [email protected] * @date 2018/7/30 */@Configurationpublic class Hirouter { @Bean public routerfunction<serverresponse> routecity (Hihandler hihandler) {return routerfunctions . Route (Requestpredicates.get ("/hi"). and (Requestpredicates.accept (mediatype.appli Cation_json)), Hihandler::hi); }}

Starting the project, you can see from the console that the two ways of mapping are printed out:

In browser access, Http://localhost:8080/hi, results:

SOURCE download: Big old Yang Code cloud

Personal website: https://www.dalaoyang.cn

Follow the author's public number

SpringBoot2 using Webflux Functional programming

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.