聊聊 Spring Boot 2.x 那些事兒

本文目錄:html

即將的 Spring 2.0前端

 - Spring 2.0 是什麼java

 - 開發環境和 IDEreact

 - 使用 Spring Initializr 快速入門git

Starter 組件程序員

 - Web:REST API & 模板引擎github

 - Data:JPA -> H2web

 - ...spring

生產指標監控 Actuatorshell

內嵌式容器 Tomcat / Jetty / Undertow

Spring 5 & Spring WebFlux

你們看到目錄,這麼多內容,簡直一本書的節奏。若是很詳細,確實是。 但是隻有一篇文章我大體講講每一個點,其是什麼,其主要業界的使用場景是什麼,而後具體會有對應的博客教程。恩,下面咱們聊聊 Spring 2.0。

1、即將的 Spring 2.0

spring.io 官網有句醒目的話是:

BUILD ANYTHING WITH SPRING BOOT

Java 程序員都知道 Spring 是什麼,Spring 走過了這麼多個年頭。Spring 是 Java 應用程序平臺開發框架,確定也是跨平臺的。

一樣,它也是 Java EE 輕量級框架,爲 Java 開發這提供了全面的基礎設施支持。

從 SSH(Strusts / Spring / Hibernate) 到 SSM(Spring MVC / Spring / Mabtis) ,到如今一個 S (Spring)就夠了的年代。 可見 Spring 愈來愈重要了。那 Spring Boot 是什麼?

1. Spring 2.0 是什麼

先看看世界上最好的文檔來源自官方的《Spring Boot Reference Guide》,是這樣介紹的:

0?wx_fmt=png

Spring Boot(英文中是「引導」的意思),是用來簡化 Spring 應用的搭建到開發的過程。應用開箱即用,只要經過 「just run」(多是 java -jar 或 tomcat 或 maven 插件 run 或 shell 腳本),就能夠啓動項目。

兩者,Spring Boot 只要不多的 Spring 配置文件(例如那些xml,property)。

由於「習慣優先於配置」的原則,使得 Spring Boot 在快速開發應用和微服務架構實踐中獲得普遍應用。

Spring 目前是 2.0.0 M5 版本,立刻 2.0 release 了。如圖:Spring 2.0 架構圖

0?wx_fmt=png

最明顯的是 Reactor 模型。

插個小故事,曾經有人問:Spring 這種阻塞的編程技術以及金字塔的結構已經開始被不少公司所擯棄?

個人回答天然是那個圖。Spring Boot 2.0 基於 Spring 5 Framework ,提供了異步非阻塞 IO 的響應式 Stream 、非堵塞的函數式 Reactive Web 框架 Spring WebFlux。本文最後我會詳細介紹的。

0?wx_fmt=png

2. 開發環境和 IDE

大體介紹了 Spring Boot 2.0 是什麼,下面咱們快速入門下 Spring Boot 2.0。常言道,磨刀不誤砍柴工砍柴工。在搭建一個 Spring Boot 工程應用前,須要配置好開發環境及安裝好開發工具:

  • JDK 1.8+
    Spring Boot 2.x 要求 JDK 1.8 環境及以上版本。另外,Spring Boot 2.x 只兼容 Spring Framework 5.0 及以上版本。

  • Maven 3.2+
    爲 Spring Boot 2.x 提供了相關依賴構建工具是 Maven,版本須要 3.2 及以上版本。使用 Gradle 則須要 1.12 及以上版本。Maven 和 Gradle 你們各自挑選下喜歡的就好。

  • IntelliJ IDEA
    IntelliJ IDEA (簡稱 IDEA)是經常使用的開發工具,也是本書推薦使用的。一樣使用 Eclipse IDE 天然也是能夠的。

這裏額外介紹下,對於 Java 新手或者剛剛認識 Spring 的小夥伴。Spring Boot CLI  是一個學習 Spring Boot 的很好的工具。Spring Boot CLI 是 Spring Boot Commad Line 的縮寫,是 Spring Boot 命令行工具。

在 Spring Boot CLI 能夠跑 Groovy 腳本,經過簡單的 Java 語法就能夠快速而又簡單的學習 Spring Boot 原型。

Spring Boot CLI  具體快速入門看下我寫的地址:https://www.bysocket.com/?p=1982

那最經常使用,最推薦的入門固然是使用 Spring Initializr 。下面介紹下如何使用 Spring Initializr。

3. 使用 Spring Initializr 快速入門

打開  start.spring.io  進行很快速的,Spring Boot 骨架工程生成吧。

Spring 官方提供了名爲 Spring Initializr 的網站,去引導你快速生成 Spring Boot 應用。網站地址爲:https://start.spring.io,操做步驟以下:

第一步,選擇 Maven 或者 Gradle 構建工具,開發語言 Java 、Kotlin 或者 Groovy,最後肯定 Spring Boot 版本號。

這裏默認選擇 Maven 構建工具、Java 開發語言和 Spring Boot 2.0.0。

第二步,輸入 Maven 工程信息,即項目組 groupId 和名字 artifactId。這裏對應 Maven 信息爲:

  • groupId:demo.springboot

  • artifactId:spring-boot-quickstart
    這裏默認版本號 version 爲 0.0.1-SNAPSHOT 。三個屬性在 Maven 依賴倉庫是惟一標識的。

第三步,選擇工程須要的 Starter 組件和其餘依賴。最後點擊生成按鈕,便可得到骨架工程壓縮包。如圖 :

0?wx_fmt=png

在對應的 *Application 增長對應的代碼以下:(這來自是官方 demo)

 

@Controller @EnableAutoConfiguration public class Application {    @RequestMapping("/")    @ResponseBody    String home() {        return "Hello World!";    }    public static void main(String[] args) throws Exception {        SpringApplication.run(Application.class, args);    } }

在 IDEA 中直接執行應用啓動類,來運行 Spring Boot 應用,會獲得下面成功的控制檯輸出:

 

... 省略 2017-10-15 10:05:19.994  INFO 17963 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) 2017-10-15 10:05:20.000  INFO 17963 --- [           main] demo.springboot.QuickStartApplication    : Started QuickStartApplication in 5.544 seconds (JVM running for 6.802)

訪問地址 localhost:8080 ,成功返回 「Hello World!」 的字符串。

這就是 Spring Boot 使用,是否是很方便。介紹下工程的目錄結構:

 

├── pom.xml └── src    ├── main    │   ├── java    │   │   └── demo    │   │       └── springboot    │   │           └── Application.java    │   └── resources    │       ├── application.properties    │       ├── static    │       └── templates    └── test        └── java            └── demo                └── springboot                    └── QuickstartApplication Tests.java

這是默認的工程結構,java 目錄中是編寫代碼的源目錄,好比三層模型大體會新建三個包目錄,web 包負責 web 服務,service 包負責業務邏輯,domain 包數據源服務。對應 java 目錄的是 test 目錄,編寫單元測試的目錄。

resources 目錄會有 application.properties 應用配置文件,還有默認生成的 static 和 templates 目錄,static 用於存放靜態資源文件,templates 用於存放模板文件。能夠在 application.properties 中自定義配置資源和模板目錄

2、Starter 組件

什麼是 Starter 組件?

Starter 組件是可被加載在應用中的 Maven 依賴項。Spring Boot 提供了不少 「開箱即用」 的 Starter 組件。只須要在 Maven 配置中添加對應的依賴配置,便可使用對應的 Starter 組件。

例如,添加 spring-boot-starter-web 依賴,就可用於構建 RESTful Web 服務,其包含了 Spring MVC 和 Tomcat 內嵌容器等。

開發中,不少功能是經過添加 Starter 組件的方式來進行實現。下面都是經常使用的組件,還有不少事務、消息、安全、監控、大數據等支持,這裏就不介紹了。你們能夠同理可得去學習哈。

1. Web:REST API & 模板引擎

在 Web 開發中,常見的場景有傳統的 Web MVC 架構和先後端分離架構。

Web MVC 架構

Web MVC 模式很適合 Spring Boot 來開發,View 使用 JSP 或者其餘模板引擎(默認支持:FreeMarker 、 Groovy 、 Thymeleaf 、 Mustache)。

傳統模式好比獲取用戶,是從用戶 view 層發送獲取用戶請求到 Spring Boot 提供的用戶控制層,而後獲取數據封裝進 Model,最後將 model 返回到 View。

由於 Spring Boot 基於 Spring ,因此 Spring 能作的,Spring Boot 就能作,並且更加方便,更近快速。

先後端分離架構

先後端分離架構,免不了的是 API 文檔做爲中間的橋樑。Spring Boot 很方便的開發 REST API,前端經過調用 REST API 獲取數據。數據形式多是 JSON 或者 XML 等。

而後進行視圖渲染,這裏前端也有對應的前端模板引擎。其實 H5 ,PC,APP 均可採起相似的方式實現。這裏的 API 文檔可使用 Swagger2 或者 APIDOC 來實現。

那具體聊聊 REST API

RESTful 是什麼?RESTful(Representational State Transfer)架構風格,是一個 Web 自身的架構風格,底層主要基於 HTTP 協議(ps:提出者就是HTTP協議的做者),是分佈式應用架構的偉大實踐理論。

RESTful 架構是無狀態的,表現爲請求-響應的形式,有別於基於 Bower 的SessionId 不一樣。Spring Boot 的註解 @RestController 支持實現 RESTful 控制層。

那有個問題?權限怎麼控制?
RESTful是無狀態的,因此每次請求就須要對起進行認證和受權。

  • 認證
    身份認證,即登陸驗證用戶是否擁有相應的身份。簡單的說就是一個Web頁面點擊登陸後,服務端進行用戶密碼的校驗。

  • 權限驗證(受權)
    也能夠說成受權,就是在身份認證後,驗證該身份具體擁有某種權限。即針對於某種資源的 CRUD,不一樣用戶的操做權限是不一樣的。

    通常簡單項目:作個sign(加密加鹽參數)+ 針對用戶的 access_token 複雜的話,加入  SLL ,並使用 OAuth2 進行對 token 的安全傳輸。

再聊聊模板引擎

有人在我博客上評論 模板語言 如今沒人用了吧。咱們仍是先了解下,什麼是模板語言再說吧。

常見的模板語言都包含如下幾個概念:數據(Data)、模板(Template)、模板引擎(Template Engine)和結果文檔(Result Documents)。

  • 數據
    數據是信息的表現形式和載體,能夠是符號、文字、數字、語音、圖像、視頻等。

    數據和信息是不可分離的,數據是信息的表達,信息是數據的內涵。數據自己沒有意義,數據只有對實體行爲產生影響時才成爲信息。

  • 模板
    模板,是一個藍圖,即一個與類型無關的類。編譯器在使用模板時,會根據模板實參對模板進行實例化,獲得一個與類型相關的類。

  • 模板引擎
    模板引擎(這裏特指用於Web開發的模板引擎)是爲了使用戶界面與業務數據(內容)分離而產生的,它能夠生成特定格式的文檔,用於網站的模板引擎就會生成一個標準的HTML文檔。

  • 結果文檔
    一種特定格式的文檔,好比用於網站的模板引擎就會生成一個標準的HTML文檔。

模板語言用途普遍,常見的用途以下:

  • 頁面渲染

  • 文檔生成

  • 代碼生成

  • 全部 「數據+模板=文本」 的應用場景

因此你們看到這個用途,應該不會說沒有用了吧。具體按模板語言 Thymeleaf 爲例,使用以下

pom.xml Thymeleaf 依賴

使用模板引擎,就在 pom.xml 加入 Thymeleaf 組件依賴:

 

<!-- 模板引擎 Thymeleaf 依賴 --> <dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>

Thymeleaf 依賴配置

在 Spring Boot 項目中加入 Thymeleaf 依賴,便可啓動其默認配置。若是想要自定義配置,能夠在 application.properties 配置以下

 

spring.thymeleaf.cache=true # Enable template caching. spring.thymeleaf.check-template=true # Check that the template exists before rendering it. spring.thymeleaf.check-template-location=true # Check that the templates location exists. spring.thymeleaf.enabled=true # Enable Thymeleaf view resolution for Web frameworks. spring.thymeleaf.encoding=UTF-8 # Template files encoding. spring.thymeleaf.excluded-view-names= # Comma-separated list of view names that should be excluded from resolution. spring.thymeleaf.mode=HTML5 # Template mode to be applied to templates. See also StandardTemplateModeHandlers. spring.thymeleaf.prefix=classpath:/templates/ # Prefix that gets prepended to view names when building a URL. spring.thymeleaf.reactive.max-chunk-size= # Maximum size of data buffers used for writing to the response, in bytes. spring.thymeleaf.reactive.media-types= # Media types supported by the view technology. spring.thymeleaf.servlet.content-type=text/html # Content-Type value written to HTTP responses. spring.thymeleaf.suffix=.html # Suffix that gets appended to view names when building a URL. spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain. spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved.

Controller 的使用方式,和之前的 Spring 方式一致,具體的Tymeleaf 的語法糖,你們能夠看看官方文檔 http://www.thymeleaf.org/documentation.html。本案例具體整合教程:https://www.bysocket.com/?p=1973。

2. Data:JPA 、Mybatis

Data,顧名思義是數據。數據存儲有 SQL 和 NoSQL:

  • SQL:MySQL 、H2 等

  • NoSQL:Redis、MongoDB、Cassandra、Elasticsearch 等
    天然互聯網常見使用的 SQL 關係型數據庫是 MySQL。ORM 框架流行的有 Hibernate 和 Mybatis 等,JPA 底層實現使用 Hibernate。下面分別介紹下二者的使用方式

Spring Data JPA 依賴 spring-boot-starter-data-jpa

Spring Data JPA 是 Spring Data 的子項目,用於簡化數據訪問層的實現,能夠方便的實現增刪改查、分頁、排序。

還有不少常見的其餘依賴:Spring Data MongoDB、Spring Data Redis 等。這裏 Spring Boot 也有對應的 Starter 組件,名爲 spring-boot-starter-data-jpa。

具體整合教程:https://www.bysocket.com/?p=1950

Spring Boot Mybatis 依賴 mybatis-spring-boot-starter

Mybatis 也是業界互聯網流行的數據操做層框架。有兩種形式進行使用 Mybatis。

第1、純 Annotation,第2、使用 xml 配置 SQL。我的推薦使用 xml 配置 SQL,  SQL 和業務代碼應該隔離,方便和 DBA 校對 SQL。兩者 XML 對較長的 SQL 比較清晰。

雖然 XML 形式是我比較推薦的,可是註解形式也是方便的。尤爲一些小系統,快速的 CRUD 輕量級的系統。這裏可見,mybatis-spring-boot-starter依賴是非官方提供的。

Springboot 整合 Mybatis 的完整 Web 案例教程:https://www.bysocket.com/?p=1610

Spring Boot 整合 Mybatis Annotation 註解的完整 Web 案例教程:https://www.bysocket.com/?p=1811

另外,搜索經常使用 ES,spring-data-elasticsearch 是 Spring Data 的 Community modules 之一,是 Spring Data 對 Elasticsearch 引擎的實現。 

Elasticsearch 默認提供輕量級的 HTTP Restful 接口形式的訪問。相對來講,使用 HTTP Client 調用也很簡單。

但 spring-data-elasticsearch 能夠更快的支持構建在 Spring 應用上,好比在 application.properties 配置 ES 節點信息和 spring-boot-starter-data-elasticsearch 依賴,直接在 Spring Boot 應用上使用。

我也寫了點系列博客在:https://www.bysocket.com/?tag=elasticsearch

還有不少組件沒法一一介紹了,好比經常使用的 Redis 作緩存操做等。

3、生產指標監控 Actuator

Starter 組件 Actuator 提供了生產級監控的特性,可使用 Actuator 來監控應用的一切。

使用方式也很簡單,加入對應的依賴,而後訪問各個 HTTP 請求就能夠獲取須要的信息。具體提供的信息有:

 

autoconfig    自動配置相關信息 beans            Spring 容器中的 Bean 相關信息 configprops     配置項信息 dump            當前線程信息 env                當前環境變量信息 health            應用的健康信息 info            應用基本信息 metrics            性能指標信息 mappings        請求路徑信息 trace            請求調用信息

至於可視化的話,可使用 http/ssh/telnet 等方式拉監控數據到可視化 UI 上便可。進一步可使用 prometheus 採集 springboot  應用指標,用 Grafana 可視化監控數據。

這裏我師弟寫一遍教程不錯:http://www.jianshu.com/p/7ecb57a3f326

4、內嵌式容器 Tomcat / Jetty / Undertow

Spring Boot 運行的應用是獨立的一個 Jar 應用,實際上在運行時啓動了應用內部的內嵌容器,容器初始化 Spring 環境及其組件並啓動應用。

但咱們也能夠自定義配置 內嵌式容器,好比將 Tomcat 換成 Jetty。Spring Boot 能這樣工做,主要靠下面兩點:自動配置和外化配置。

自動配置

Spring Boot 在不須要任何配置狀況下,就直接能夠運行一個應用。實際上,Spring Boot 框架的 spring-boot-autoconfigure 依賴作了不少默認的配置項,即應用默認值。這種模式叫作 「自動配置」。

Spring Boot 自動配置會根據添加的依賴,自動加載依賴相關的配置屬性並啓動依賴。例如,默認用的內嵌式容器是 Tomcat ,端口默認設置爲 8080。

外化配置

Spring Boot 簡化了配置,在 application.properties 文件配置經常使用的應用屬性。Spring Boot 能夠將配置外部化,這種模式叫作 「外化配置」。

將配置從代碼中分離外置,最明顯的做用是隻要簡單地修改下外化配置文件,就能夠在不一樣環境中,能夠運行相同的應用代碼。

因此,Spring Boot 啓動應用,默認狀況下是自動啓動了內嵌容器 Tomcat,而且自動設置了默認端口爲 8080。

另外還提供了對 Jetty、Undertow 等容器的支持。開發者自行在添加對應的容器 Starter 組件依賴,便可配置並使用對應內嵌容器實例。具體操做以下:

第一步,將 tomcat 依賴排除:

 

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-web</artifactId>    <exclusions>        <exclusion>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-tomcat</artifactId>        </exclusion>    </exclusions> </dependency>

spring-boot-starter-web 依賴默認使用 Tomcat 做爲內嵌容器

第二步,加入對應的 jetty 依賴(這裏也能夠是 Undertow 依賴)

 

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-jetty</artifactId> </dependency>

上面大體介紹了 Spring Boot 2.0 有的那些特性,也就是那些事,最後入門介紹下 WebFlux。

5、Spring 5 & Spring WebFlux

最後,Spring Boot 2.0 支持 Spring 5,Spring 5 具備了強大的特性:WebFlux/Reactor。因此最後來聊聊 WebFlux ,就算入個門吧。

對照下 Spring Web MVC ,Spring Web MVC 是基於 Servlet API 和 Servlet 容器設計的。那麼 Spring WebFlux 確定不是基於前面二者,它基於 Reactive Streams API  和 Servlet 3.1+ 容器設計。

那 Reactive Streams API 是什麼?

先理解 Stream 流是什麼?流是序列,是生產者生產,一個或多個消費者消費的元素序列。這種具體的設計模式成爲發佈訂閱模式。常見的流處理機制是 pull / push 模式。背壓是一種經常使用策略,使得發佈者擁有無限制的緩衝區存儲 item,用於確保發佈者發佈 item 太快時,不會去壓制訂閱者。

Reactive Streams (響應式流)是提供處理非阻塞背壓異步流的一種標準。主要針對的場景是運行時環境(包括 JVM 和 JS)和網絡。一樣,JDK 9 java.util.concurrent 包提供了兩個主要的 API 來處理響應流:

  • Flow

  • SubmissionPublisher

     

爲啥只能運行在 Servlet 3.1+ 容器?

你們知道,3.1 規範其中一個新特性是異步處理支持。

異步處理支持:Servlet 線程不需一直阻塞,即不須要到業務處理完畢再輸出響應,而後結束 Servlet線程。

異步處理的做用是在接收到請求以後,Servlet 線程能夠將耗時的操做委派給另外一個線程來完成,在不生成響應的狀況下返回至容器。

主要應用場景是針對業務處理較耗時的狀況,能夠減小服務器資源的佔用,而且提升併發處理速度。

因此 WebFlux 支持的容器有 Tomcat、Jetty(Non-Blocking IO API) ,也能夠像 Netty 和 Undertow 的自己就支持異步容器。在容器中 Spring WebFlux 會將輸入流適配成 Mono 或者 Flux 格式進行統一處理。

Spring WebFlux 是什麼

0?wx_fmt=png

先看這張圖,上面咱們瞭解了容器、響應流。這裏介紹下 Spring WebFlux 是什麼? Spring WebFlux 是 Spring 5 的一個新模塊,包含了響應式 HTTP 和 WebSocket 的支持,另外在上層服務端支持兩種不一樣的編程模型:

  • 基於 Spring MVC 註解 @Controller 等

  • 基於 Functional 函數式路由

下面是兩個實現小案例,首先在 pom.xml 加入對應的依賴:

 

  <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-webflux</artifactId>    </dependency>

基於 Spring MVC 註解 RESTful API

官方案例很簡單,以下:

 

@RestController public class PersonController {        private final PersonRepository repository;        public PersonController(PersonRepository repository) {                this.repository = repository;        }        @PostMapping("/person")        Mono<Void> create(@RequestBody Publisher<Person> personStream) {                return this.repository.save(personStream).then();        }        @GetMapping("/person")        Flux<Person> list() {                return this.repository.findAll();        }        @GetMapping("/person/{id}")        Mono<Person> findById(@PathVariable String id) {                return this.repository.findOne(id);        } }

可是 PersonRepository 這種 Spring Data Reactive Repositories 不支持 MySQL,進一步也不支持 MySQL 事務。因此用了 Reactivey 原來的 spring 事務管理就很差用了。

jdbc jpa 的事務是基於阻塞 IO 模型的,若是 Spring Data Reactive  沒有升級 IO 模型去支持 JDBC,生產上的應用只能使用不強依賴事務的。

也可使用透明的事務管理,即每次操做的時候以回調形式去傳遞數據庫鏈接 connection。

Spring Data Reactive Repositories  目前支持 Mongo、Cassandra、Redis、Couchbase 。

若是應用只能使用不強依賴數據事務,依舊使用 MySQL ,可使用下面的實現,代碼以下:

 

@RestController @RequestMapping(value = "/city") public class CityRestController {    @Autowired    private CityService cityService;    @RequestMapping(value = "/{id}", method = RequestMethod.GET)    public Mono<City> findOneCity(@PathVariable("id") Long id) {        return Mono.create(cityMonoSink -> cityMonoSink.success(cityService.findCityById(id)));    }    @RequestMapping(method = RequestMethod.GET)    public Flux<City> findAllCity() {        return Flux.create(cityFluxSink -> {            cityService.findAllCity().forEach(city -> {                cityFluxSink.next(city);            });            cityFluxSink.complete();        });    }    @RequestMapping(method = RequestMethod.POST)    public Mono<Long> createCity(@RequestBody City city) {        return Mono.create(cityMonoSink -> cityMonoSink.success(cityService.saveCity(city)));    }    @RequestMapping(method = RequestMethod.PUT)    public Mono<Long> modifyCity(@RequestBody City city) {        return Mono.create(cityMonoSink -> cityMonoSink.success(cityService.updateCity(city)));    }    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)    public Mono<Long> modifyCity(@PathVariable("id") Long id) {        return Mono.create(cityMonoSink -> cityMonoSink.success(cityService.deleteCity(id)));    } }

findAllCity 方法中,利用 Flux.create 方法對響應進行建立封裝成 Flux 數據。而且使用 lambda 寫數據流的處理函數會十分的方便。

Service 層依舊是之前那套邏輯,業務服務層接口以下:

 

public interface CityService {    /**     * 獲取城市信息列表     *     * @return     */    List<City> findAllCity();    /**     * 根據城市 ID,查詢城市信息     *     * @param id     * @return     */    City findCityById(Long id);    /**     * 新增城市信息     *     * @param city     * @return     */    Long saveCity(City city);    /**     * 更新城市信息     *     * @param city     * @return     */    Long updateCity(City city);    /**     * 根據城市 ID,刪除城市信息     *     * @param id     * @return     */    Long deleteCity(Long id); }

具體案例在個人 Github:https://github.com/JeffLi1993/springboot-learning-example

基於 Functional 函數式路由實現 RESTful API

建立一個 Route 類來定義 RESTful HTTP 路由:

 

import static org.springframework.web.reactive.function.server.RequestPredicates.GET; import static org.springframework.web.reactive.function.server.RequestPredicates.accept; import static org.springframework.web.reactive.function.server.RouterFunctions.route; @Configuration public class Routes {    private CityService cityService;    public Routes(CityService cityService) {        this.cityService = cityService;    }    @Bean    public RouterFunction<?> routerFunction() {        return route(                       GET("/api/city").and(accept(MediaType.APPLICATION_JSON)), cityService:: findAllCity).and(route(                       GET("/api/user/{id}").and(accept(MediaType.APPLICATION_JSON)), cityService:: findCityById)                );    } }

RoouterFunction 相似 Spring Web MVC 的 @RequestMapping ,用來定義路由信息,每一個路由會映射到一個處理方法,當接受 HTTP 請求時候會調用該處理方法。

建立 HttpServerConfig 自定義 Http Server,這裏建立一個 Netty HTTP 服務器:

 

import org.springframework.http.server.reactive.HttpHandler; import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter; import reactor.ipc.netty.http.server.HttpServer; @Configuration public class HttpServerConfig {    @Autowired    private Environment environment;    @Bean    public HttpServer httpServer(RouterFunction<?> routerFunction) {        HttpHandler httpHandler = RouterFunctions.toHttpHandler(routerFunction);        ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler);        HttpServer server = HttpServer.create("localhost", Integer.valueOf(environment.getProperty("server.port")));        server.newHandler(adapter);        return server;    } }

天然推薦 Netty 來運行 Reactive 應用,由於 Netty 是基於異步和事件驅動的。

從案例中,你們也簡單入門瞭解 WebFlux

小結

謝謝你們的閱讀,本文寫的不是那麼精緻。期待過幾天和你們微信溝通交流學習。

by the way , 最近在寫一本小小書,《Spring Boot 2.x 核心技術實戰(上)基礎篇》,針對基礎實踐,精緻地寫了 demo 和講解。

最後仍是謝謝。

 

http://blog.csdn.net/GitChat/article/details/78454120

相關文章
相關標籤/搜索