SpringBoot2使用WebFlux函數式編程

本文只是簡單使用SpringBoot2使用WebFlux的函數式編程簡單使用,后續會繼續寫關于Webflux相關的文章。

最近一直在研究WebFlux,后續會陸續出一些相關的文章。

首先看一下Srping官網上的一張圖,對比一下SpringMvc和Spring WebFlux,如圖:

在查看一下WebFlux的官方文檔:docs.spring.io/spring/docs…,WebFlux提供了函數式編程,本文簡單介紹一下WebFlux函數式編程簡單使用。

新建項目

創建一個項目,pom文件中引入webflux依賴,完整pom文件如下:

<?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>springboot2_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 --></parent><properties><project.build.sourceEncoding>UTF-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><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-webflux</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
復制代碼

首先試試引入WebFlux依賴之后,SpringMvc方式是否還能使用,新建一個HelloController,完整代碼如下,執行后發現,是可以正常執行訪問的,這其實就是我們所說的注解式編程。

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 yangyang@dalaoyang.cn* @date 2018/7/30*/
@RestController
public class HelloController {@GetMapping("hello")public String Hello(){return "Hello this is SpringWebFlux";}}
復制代碼

結果如圖:

接下來使用函數式編程,首先查閱一下官方文檔,如圖:

我們需要創建一個HandlerFunction返回值為Mono,新建一個HiHandler,里面寫一個方法Hi,完整代碼如下:

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 yangyang@dalaoyang.cn* @date 2018/7/30*/
@Component
public class HiHandler {public Mono<ServerResponse> Hi(ServerRequest request) {return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(BodyInserters.fromObject("Hi , this is SpringWebFlux"));}
}
復制代碼

其中ServerResponse是相應的封裝對象,下面是它的源碼,其中包含了響應狀態,響應頭等等,代碼如下:

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(HttpStatus.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(HttpStatus.SEE_OTHER);return (ServerResponse.BodyBuilder)builder.location(location);}static ServerResponse.BodyBuilder temporaryRedirect(URI location) {ServerResponse.BodyBuilder builder = status(HttpStatus.TEMPORARY_REDIRECT);return (ServerResponse.BodyBuilder)builder.location(location);}static ServerResponse.BodyBuilder permanentRedirect(URI location) {ServerResponse.BodyBuilder builder = status(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<HttpMessageWriter<?>> messageWriters();List<ViewResolver> viewResolvers();}public interface BodyBuilder extends ServerResponse.HeadersBuilder<ServerResponse.BodyBuilder> {ServerResponse.BodyBuilder contentLength(long var1);ServerResponse.BodyBuilder contentType(MediaType var1);ServerResponse.BodyBuilder hint(String var1, Object var2);<T, P extends Publisher<T>> Mono<ServerResponse> body(P var1, Class<T> var2);<T, P extends Publisher<T>> Mono<ServerResponse> body(P var1, ParameterizedTypeReference<T> var2);Mono<ServerResponse> syncBody(Object var1);Mono<ServerResponse> body(BodyInserter<?, ? super ServerHttpResponse> var1);Mono<ServerResponse> render(String var1, Object... var2);Mono<ServerResponse> render(String var1, Map<String, ?> var2);}public interface HeadersBuilder<B extends ServerResponse.HeadersBuilder<B>> {B header(String var1, String... var2);B headers(Consumer<HttpHeaders> var1);B cookie(ResponseCookie var1);B cookies(Consumer<MultiValueMap<String, ResponseCookie>> var1);B allow(HttpMethod... var1);B allow(Set<HttpMethod> var1);B eTag(String var1);B lastModified(ZonedDateTime var1);B location(URI var1);B cacheControl(CacheControl var1);B varyBy(String... var1);Mono<ServerResponse> build();Mono<ServerResponse> build(Publisher<Void> var1);Mono<ServerResponse> build(BiFunction<ServerWebExchange, ServerResponse.Context, Mono<Void>> var1);}
}
復制代碼

在回過頭了看上面官方文檔的圖片,還需要配置一個路由來類似@RequestMapping的功能,通過RouterFunctions.route(RequestPredicate, HandlerFunction)提供了一個路由器函數默認實現,新建一個HiRouter,代碼如下:

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 yangyang@dalaoyang.cn* @date 2018/7/30*/
@Configuration
public class HiRouter {@Beanpublic RouterFunction<ServerResponse> routeHi(HiHandler hiHandler) {return RouterFunctions.route(RequestPredicates.GET("/hi").and(RequestPredicates.accept(MediaType.APPLICATION_JSON)),hiHandler::Hi);}
}
復制代碼

啟動項目,通過控制臺可以看到,兩種方式的映射都被打印出來了,如圖所示:

在瀏覽器訪問,http://localhost:8080/hi,結果如圖所示:

源碼下載 :大老楊碼云

個人網站:www.dalaoyang.cn

關注作者公眾號

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/451060.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/451060.shtml
英文地址,請注明出處:http://en.pswp.cn/news/451060.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

單點登錄原理與簡單實現

前些天發現了一個巨牛的人工智能學習網站&#xff0c;通俗易懂&#xff0c;風趣幽默&#xff0c;忍不住分享一下給大家。點擊跳轉到教程。 一、單系統登錄機制 1、http無狀態協議 web應用采用browser/server架構&#xff0c;http作為通信協議。http是無狀態協議&#xff0c;瀏…

java接口類支持多繼承

一個類只能extends一個父類&#xff0c;只能有一個父類&#xff0c;但可以implements多個接口。java通過使用接口的概念來取代C中多繼承。與此同時&#xff0c;一個接口則可以同時extends多個接口&#xff0c;卻不能implements任何接口。Java中的接口是支持多繼承的。

xmind-HTTP協議

轉載于:https://www.cnblogs.com/margot921/p/9764788.html

彈性布局

彈性布局 一、Flex布局是什么&#xff1f; Flex是Flexible Box的縮寫&#xff0c;意為”彈性布局”&#xff0c;用來為盒狀模型提供最大的靈活性。任何一個容器都可以指定為Flex布局。 二、基本概念 采用Flex布局的元素&#xff0c;稱為Flex容器&#xff08;flex container&…

Java-Type簡單分類

&#xff08;1&#xff09;ParameterizedType&#xff1a; 參數化類型&#xff0c;例如List<T>。 &#xff08;2&#xff09;GenericArrayType&#xff1a; 泛型數組類型&#xff0c;例如T[]。 &#xff08;3&#xff09;TypeVariable&#xff1a; 泛型的類型變量&a…

解決dataTable 報錯:cannot read property “style“ of undefined

前些天發現了一個巨牛的人工智能學習網站&#xff0c;通俗易懂&#xff0c;風趣幽默&#xff0c;忍不住分享一下給大家。點擊跳轉到教程。 其實這錯&#xff0c;我之前也遇到過&#xff0c;只是太久了&#xff0c;沒有記錄下來&#xff0c; 今天看到群里朋友也遇到這個錯誤&a…

萬惡之源 - Python基礎數據類型一

整數 整數在Python中的關鍵字用int來表示; 整型在計算機中運于計算和比較 在32位機器上int的范圍是: -2**31&#xff5e;2**31-1&#xff0c;即-2147483648&#xff5e;2147483647 在64位機器上int的范圍是: -2**63&#xff5e;2**63-1&#xff0c;即-9223372036854775808&…

談談對于技術面試的心得體驗

導讀&#xff1a;作者lzprgmr寫了一篇《談談技術面試》文章&#xff0c;他在文中講述了自己對于技術人員面試的經驗和心得&#xff0c;以下是文章內容&#xff1a; 只要是招一個技術人員&#xff0c;不管是初級的程序員還是高級軟件工程師&#xff0c;技術上的考核都必不可少。…

es6中class類的全方面理解(三)------靜態方法

不需要實例化類&#xff0c;即可直接通過該類來調用的方法&#xff0c;即稱之為“靜態方法”。將類中的方法設為靜態方法也很簡單&#xff0c;在方法前加上static關鍵字即可。這樣該方法就不會被實例繼承&#xff01; class Box{static a(){return "我是Box類中的&#xf…

jackson/fastJson boolean類型問題

1.我們以Person對象舉個栗子&#xff0c;person有三個屬性。name&#xff0c;age和isGay Data public class Person {public Person(String name, int age, boolean isGay) {this.name name;this.age age;this.isGay isGay;}private String name;private Integer age;priva…

django模板系統(下)

主要內容&#xff1a;母版&#xff0c;繼承母版&#xff0c;塊&#xff0c;組件&#xff0c;靜態文件 母版 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta http-equiv"x-ua-compatible" conten…

狗窩里的小日子 ...

來&#xff0c;把平時作的菜菜整理下下&#xff1a; 1. 2. 3. 4. 5. 6. 7. 8.

面試開發人員的有效方法

伯樂在線 寫道 "Alan Skorkin是一名軟件開發人員&#xff0c;這是他分享的另一篇有關面試和開發人員的文章(中文)。Skorkin 認為&#xff0c;“當要雇傭開發者時&#xff0c;傳統的面試方法顯得力不從心&#xff0c;這是必須要面對的現實。為什么不行&#xff1f;原因也許…

Android直接用手機打包apk!

你沒有看錯&#xff0c;用手機瀏覽器訪問Jenkins&#xff0c;就可以打包apk&#xff0c;并生成下載二維碼&#xff0c;發送郵件通知測試人員下載&#xff0c;從此解放雙手&#xff0c;告別打包測試。先上本人手機郵箱收到的打包成功通知效果圖&#xff1a; 廢話少說&#xff0c…

java中byte、short、char、boolean實際都是按照int處理的!

byte、char、short、boolean四種類型在匯編期或運行期間采取和int類型一樣的存儲方式&#xff0c;在計算時會先轉換為int類型&#xff0c;后進行計算。所以兩個short類型數據做算數運算&#xff0c;結果卻為int類型。這主要是因為jvm的字節碼為了簡潔高效&#xff0c;設計時只使…

4、2 核心組件

1、Stage&#xff1a;虛的  一組RDD構成的鏈條并行的task集合&#xff0c;同一Stage的所有任務有著相同的Shuffle依賴。階段的劃分按照shuffle標記來進行的。一個階段含多個RDD&#xff0c;先有RDD后有Stage一個階段含多個taskstage通過ShuffleDependency劃分&#xff0c;一個…

狗窩里的小日子- 2 ...

來&#xff0c;把平時作的菜菜整理下&#xff1a; 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20.

優秀程序員必備素質——快速調試

你是否有過這些經歷&#xff1a; 1.代碼敲完了&#xff0c;剛想松口氣&#xff0c;一運行程序&#xff0c;滿滿的Bug。 2.找啊找啊找&#xff0c;怎么找都找不到哪里出了問題。 3.調試了半天出不來&#xff0c;就開始便得心煩氣躁。 4.一天連一個Bug也沒調出來&#xff0c;…

Java程序編譯運行過程

整體流程 1.首先由源程序文件編譯成class文件。注意這里的源程序并不僅限于java程序&#xff0c;其他語言如果能夠編譯成class文件&#xff0c;并且符合jvm規范也能夠在jvm上運行。 2.jvm將class文件拷貝到內存&#xff0c;解釋成相應的機器語言運行。我們常用的hotspot虛擬機…

【TeeChart .NET教程】(七)使用函數

2019獨角獸企業重金招聘Python工程師標準>>> 上一篇&#xff1a;【TeeChart .NET教程】&#xff08;六&#xff09;使用系列 【下載TeeChart.Net最新版本】 &#xff08;一&#xff09;功能類型 1.1 功能類型 TeeChart Pro功能是一個系列&#xff0c;幾乎可以是任何…