初探Spring Cloud Gateway實(shí)戰(zhàn)
關(guān)于Spring Cloud Gateway
- 這是一個(gè)基于Spring技術(shù)棧構(gòu)建的API網(wǎng)關(guān),涉及到:Spring5、Spring Boot 2、Reactor等,目標(biāo)是為項(xiàng)目提供簡(jiǎn)單高效的API路由,以及強(qiáng)大的擴(kuò)展能力:安全、監(jiān)控、彈性計(jì)算等
- 官方架構(gòu)圖如下,可見(jiàn)請(qǐng)求到來(lái)后,由Handler Mapping決定請(qǐng)求對(duì)應(yīng)的真實(shí)目標(biāo),然后交給Web Handler,由一系列過(guò)濾器(filter)執(zhí)行鏈?zhǔn)教幚恚瑥募t色箭頭和注釋可以發(fā)現(xiàn),請(qǐng)求前后都有過(guò)濾器在運(yùn)行:
版本信息
- 《Spring Cloud Gateway實(shí)戰(zhàn)》系列涉及的軟件和庫(kù)版本信息如下:
- 本篇實(shí)戰(zhàn)涉及到的主要版本情況如下:
1.JDK:1.8.0_291
2.IDEA:2021.1.3 (Ultimate Edition)
3.maven:3.8.1
4.操作系統(tǒng):win10 64位
5.springboot:2.4.2
6.spring-cloud:2020.0.1
7.spring-cloud-alibaba:2021.1
經(jīng)典配置中的核心概念
- 先通過(guò)一個(gè)典型的簡(jiǎn)化版配置來(lái)了解幾個(gè)核心概念,假設(shè)Spring Cloud Gateway應(yīng)用正在運(yùn)行,監(jiān)聽(tīng)8080端口,一旦有遠(yuǎn)程請(qǐng)求來(lái)到8080端口,下面的配置就會(huì)生效了,三個(gè)核心概念,以及每個(gè)配置的作用,請(qǐng)參考中文注釋?zhuān)?/li>
spring: cloud: gateway: # 核心概念1:路由,一個(gè)路由代表一個(gè)處理邏輯, # 該邏輯里面包含三個(gè)元素:匹配條件(是否該此路由處理)、真實(shí)處理地址、過(guò)濾器 routes: # id要確保唯一性 - id: add_request_header_route # 真實(shí)處理地址,請(qǐng)求一旦確定是當(dāng)前路由處理,就會(huì)轉(zhuǎn)發(fā)到這個(gè)地址去 uri: https://example.org # 核心概念2:謂語(yǔ)或者斷言,作用是判斷請(qǐng)求是否由當(dāng)前路由處理 predicates: # 這是斷言的一種,檢查請(qǐng)求的Cookie中mycookie的值是否等于mycookievalue - Cookie=mycookie,mycookievalue # 核心概念3:過(guò)濾器,請(qǐng)求前和請(qǐng)求后都可以有過(guò)濾器處理請(qǐng)求響應(yīng)數(shù)據(jù) filters: # 這個(gè)過(guò)濾器的作用是在請(qǐng)求header中添加一個(gè)鍵值對(duì),值等于"aaabbbccc" - AddRequestHeader=X-Request-Red, aaabbbccc
- 上述配置信息中的predicates是簡(jiǎn)化版配置,和完整配置對(duì)比效果如下,簡(jiǎn)單的說(shuō)就是把一行拆成了三項(xiàng):name、args.name、args.regexp
- 理論知識(shí)點(diǎn)到為止,咱們還是盡快動(dòng)手吧
啟動(dòng)nacos-2.0.3
- 整個(gè)《pring Cloud Gateway實(shí)戰(zhàn)》系列,我們會(huì)涉及到多個(gè)服務(wù),這就不可避免的會(huì)用到注冊(cè)中心和配置中心,這里我選擇了nacos,它可以很好地承擔(dān)注冊(cè)中心和配置中心的角色,接下來(lái)介紹如何部署和啟動(dòng)nacos
- 下載nacos,地址是:https://github.com/alibaba/nacos/releases/download/2.0.3/nacos-server-2.0.3.zip
- 解壓后進(jìn)入nacos\bin目錄,執(zhí)行以下命令啟動(dòng)nacos:
startup.cmd -m standalone
如果您的電腦是mac或者linux,請(qǐng)執(zhí)行以下命令啟動(dòng)nacos:
sh startup.sh -m standalone
- 瀏覽器登錄nacos,地址是http://localhost:8848/nacos,賬號(hào)和密碼都是nacos
- 登錄成功后顯示如下:
源碼下載
本篇實(shí)戰(zhàn)中的完整源碼可在GitHub下載到,地址和鏈接信息如下表所示(https://github.com/zq2599/blog_demos):
名稱(chēng) | 鏈接 | 備注 |
---|---|---|
項(xiàng)目主頁(yè) | https://github.com/zq2599/blog_demos | 該項(xiàng)目在GitHub上的主頁(yè) |
git倉(cāng)庫(kù)地址(https) | https://github.com/zq2599/blog_demos.git | 該項(xiàng)目源碼的倉(cāng)庫(kù)地址,https協(xié)議 |
git倉(cāng)庫(kù)地址(ssh) | git@github.com:zq2599/blog_demos.git | 該項(xiàng)目源碼的倉(cāng)庫(kù)地址,ssh協(xié)議 |
這個(gè)git項(xiàng)目中有多個(gè)文件夾,本篇的源碼在spring-cloud-tutorials文件夾下,如下圖紅框所示:
《Spring Cloud Gateway實(shí)戰(zhàn)》系列的父工程
新建名為spring-cloud-tutorials的maven工程,這就是《Spring Cloud Gateway實(shí)戰(zhàn)》系列所有源碼的父工程就,pom.xml內(nèi)容如下,可見(jiàn)這里將springboot、spring-cloud、spring-cloud-alibaba庫(kù)的版本號(hào)都已經(jīng)確定,今后子工程就無(wú)需關(guān)注依賴(lài)庫(kù)的版本號(hào)了:
<?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> <modules> <module>hello-gateway</module> <module>provider-hello</module> <module>common</module> </modules> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.2</version> <relativePath/> </parent> <groupId>com.bolingcavalry</groupId> <artifactId>spring-cloud-tutorials</artifactId> <version>1.0-SNAPSHOT</version> <properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> <java.version>1.8</java.version> <spring-cloud.version>2020.0.1</spring-cloud.version> <spring-cloud-alibaba.version>2021.1</spring-cloud-alibaba.version> </properties> <packaging>pom</packaging> <description>Demo project for Spring Cloud </description> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-dependencies</artifactId> <version>${spring-cloud-alibaba.version}</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.14.9</version> <scope>compile</scope> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.1.7</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.16</version> </dependency> </dependencies> </dependencyManagement> </project>
創(chuàng)建名為common的子工程,存放共用的常量和數(shù)據(jù)結(jié)構(gòu)
- 現(xiàn)在創(chuàng)建名為common的子工程,整個(gè)《Spring Cloud Gateway實(shí)戰(zhàn)》系列涉及的常量和數(shù)據(jù)結(jié)構(gòu)都放在這個(gè)子工程中,方便其他工程使用
- 新增常量Constants.java:
package com.bolingcavalry.common; public interface Constants { String HELLO_PREFIX = "Hello World"; }
創(chuàng)建web應(yīng)用,作為服務(wù)提供方
- 現(xiàn)在創(chuàng)建名為provider-hello的web應(yīng)用,這是個(gè)極其普通的web應(yīng)用,提供幾個(gè)http接口服務(wù),咱們?cè)趪L試Spring Cloud Gateway的基本功能時(shí),都會(huì)將請(qǐng)求路由到provider-hello上來(lái)
- provider-hello是個(gè)普通的springboot應(yīng)用,會(huì)在nacos進(jìn)行注冊(cè),其pom.xml內(nèi)容如下:
<?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"> <parent> <artifactId>spring-cloud-tutorials</artifactId> <groupId>com.bolingcavalry</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>provider-hello</artifactId> <packaging>jar</packaging> <dependencies> <dependency> <groupId>com.bolingcavalry</groupId> <artifactId>common</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--nacos:用于服務(wù)注冊(cè)與發(fā)現(xiàn)--> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <!-- 如果父工程不是springboot,就要用以下方式使用插件,才能生成正常的jar --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <mainClass>com.bolingcavalry.provider.ProviderApplication</mainClass> </configuration> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>
工程的配置文件application.yml如下,web端口是8082,還有一處要注意的是nacos服務(wù)地址:
server: #服務(wù)端口 port: 8082 spring: application: name: provider-hello cloud: nacos: discovery: # nacos服務(wù)地址 server-addr: 127.0.0.1:8848
- 啟動(dòng)類(lèi)ProviderApplication.java
package com.bolingcavalry.provider; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @SpringBootApplication public class ProviderApplication { public static void main(String[] args) { SpringApplication.run(ProviderApplication.class, args); } }
- 普通的Controller類(lèi)Hello.java,對(duì)外提供一個(gè)http服務(wù):
package com.bolingcavalry.provider.controller; import com.bolingcavalry.common.Constants; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.text.SimpleDateFormat; import java.util.Date; @RestController @RequestMapping("/hello") public class Hello { private String dateStr(){ return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()); } /** * 返回字符串類(lèi)型 * @return */ @GetMapping("/str") public String helloStr() { return Constants.HELLO_PREFIX + ", " + dateStr(); } }
新增測(cè)試類(lèi)HelloTest.java,用于檢查應(yīng)用的服務(wù)是否正常:
package com.bolingcavalry.provider.controller; import com.bolingcavalry.common.Constants; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import static org.hamcrest.Matchers.containsString; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @SpringBootTest @AutoConfigureMockMvc @Slf4j class HelloTest { @Autowired private MockMvc mvc; @Test void hello() throws Exception { String responseString = mvc.perform(MockMvcRequestBuilders.get("/hello/str").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(containsString(Constants.HELLO_PREFIX))) .andDo(print()) .andReturn() .getResponse() .getContentAsString(); log.info("response in junit test :\n" + responseString); } }
執(zhí)行單元測(cè)試(此時(shí)nacos是否啟動(dòng)無(wú)所謂,只是不啟動(dòng)的話(huà)控制臺(tái)會(huì)有一些錯(cuò)誤信息,但是沒(méi)有影響),如下,測(cè)試通過(guò)表示服務(wù)是正常的:
開(kāi)發(fā)一個(gè)簡(jiǎn)單的demo,完成spring-cloud-gateway的初體驗(yàn)
- 前面做了那么多準(zhǔn)備,接下來(lái)咱們會(huì)投入到Spring Cloud Gateway的開(kāi)發(fā)中,先寫(xiě)個(gè)簡(jiǎn)單的demo快速體驗(yàn)一下
- 新增名為hello-gateway的子工程,pom.xml如下,重點(diǎn)是依賴(lài)了spring-cloud-starter-gateway庫(kù),還有一處要重點(diǎn)小心的:測(cè)試庫(kù)用的是reactor-test和spring-boot-starter-test,這和之前的單元測(cè)試很不一樣,用的是webflux:
<?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"> <parent> <artifactId>spring-cloud-tutorials</artifactId> <groupId>com.bolingcavalry</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>hello-gateway</artifactId> <dependencies> <dependency> <groupId>com.bolingcavalry</groupId> <artifactId>common</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <dependency> <groupId>io.projectreactor</groupId> <artifactId>reactor-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> </project>
- 下面是重點(diǎn),Spring Cloud Gateway的配置文件application.yml,:
server: #服務(wù)端口 port: 8081 spring: application: name: hello-gateway cloud: gateway: routes: - id: path_route # 匹配成功后,會(huì)被轉(zhuǎn)發(fā)到8082端口,至于端口后面的path,會(huì)直接使用原始請(qǐng)求的 # 例如http://127.0.0.1:8081/hello/str,會(huì)被轉(zhuǎn)發(fā)到http://127.0.0.1:8082/hello/str uri: http://127.0.0.1:8082 predicates: # 根據(jù)請(qǐng)求路徑中帶有"/hello/",就算匹配成功 - Path=/hello/**
如果要轉(zhuǎn)發(fā)到其他域名下,需要?jiǎng)?chuàng)建配置類(lèi)解決跨域問(wèn)題:
package com.bolingcavalry.hellogateway.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.reactive.CorsWebFilter; import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource; import org.springframework.web.util.pattern.PathPatternParser; @Configuration public class CorsConfig { @Bean public CorsWebFilter corsFilter() { CorsConfiguration config = new CorsConfiguration(); config.addAllowedMethod("*"); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser()); source.registerCorsConfiguration("/**", config); return new CorsWebFilter(source); } }
- 啟動(dòng)類(lèi):
package com.bolingcavalry.hellogateway; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class HelloGatewayApplication { public static void main(String[] args) { SpringApplication.run(HelloGatewayApplication.class,args); } }
- 最后是單元測(cè)試類(lèi),請(qǐng)注意,由于Spring Cloud Gateway使用了webflux技術(shù)棧,因此不能用常見(jiàn)的MockMvc來(lái)模擬請(qǐng)求,幾個(gè)注解也值得注意,另外也要注意WebTestClient的expectStatus、expectBody等API的用法:
package com.bolingcavalry.hellogateway; import com.bolingcavalry.common.Constants; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.reactive.server.WebTestClient; import static org.junit.jupiter.api.Assertions.assertTrue; @SpringBootTest @ExtendWith(SpringExtension.class) @AutoConfigureWebTestClient public class HelloTest { @Autowired private WebTestClient webClient; @Test void testHelloPredicates() { webClient.get() .uri("/hello/str") .accept(MediaType.APPLICATION_JSON) .exchange() // 驗(yàn)證狀態(tài) .expectStatus().isOk() // 驗(yàn)證結(jié)果,注意結(jié)果是字符串格式 .expectBody(String.class).consumeWith(result -> assertTrue(result.getResponseBody().contains(Constants.HELLO_PREFIX))); } }
請(qǐng)確保provider-hello應(yīng)用已經(jīng)啟動(dòng),再運(yùn)行上面創(chuàng)建的HelloTest.java,得到結(jié)果如下,測(cè)試通過(guò),證明hello-gateway的功能符合預(yù)期,成功的將請(qǐng)求轉(zhuǎn)發(fā)到provider-hello應(yīng)用,并且成功收到響應(yīng):
至此,《Spring Cloud Gateway實(shí)戰(zhàn)》系列的準(zhǔn)備工作已經(jīng)完成,而且開(kāi)發(fā)了一個(gè)簡(jiǎn)單的應(yīng)用體驗(yàn)最基本的Spring Cloud Gateway功能,接下來(lái)的文章,咱們一起實(shí)戰(zhàn)更多基本功能。
總結(jié)
本篇文章就到這里了,希望能給你帶來(lái)幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
Java實(shí)現(xiàn)四則混合運(yùn)算代碼示例
這篇文章主要介紹了Java實(shí)現(xiàn)四則混合運(yùn)算代碼示例,文中展示了詳細(xì)代碼,具有一定參考價(jià)值,需要的朋友可以了解下。2017-10-10java命令調(diào)用虛擬機(jī)方法總結(jié)
在本篇文章里我們給大家整理了關(guān)于java中的java命令如何調(diào)用虛擬機(jī)的方法和具體步驟,需要的朋友們跟著操作下。2019-05-05解決idea使用maven編譯正常但是運(yùn)行項(xiàng)目時(shí)卻提示很多jar包找不到的問(wèn)題
這篇文章主要介紹了解決idea使用maven編譯正常但是運(yùn)行項(xiàng)目時(shí)卻提示很多jar包找不到的問(wèn)題,本文分多種情形給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-07-07JWT在OpenFeign調(diào)用中進(jìn)行令牌中繼詳解
Feign是一個(gè)聲明式的Web Service客戶(hù)端,是一種聲明式、模板化的HTTP客戶(hù)端。而OpenFeign是Spring Cloud 在Feign的基礎(chǔ)上支持了Spring MVC的注解,如@RequesMapping等等,這篇文章主要給大家介紹了關(guān)于JWT在OpenFeign調(diào)用中進(jìn)行令牌中繼的相關(guān)資料,需要的朋友可以參考下2021-10-10Spring MVC 中 AJAX請(qǐng)求并返回JSON的示例
本篇文章主要介紹了Spring MVC 中 AJAX請(qǐng)求并返回JSON,具有一定的參考價(jià)值,有興趣的可以了解一下。2017-01-01Jmeter多臺(tái)機(jī)器并發(fā)請(qǐng)求實(shí)現(xiàn)壓力性能測(cè)試
這篇文章主要介紹了Jmeter多臺(tái)機(jī)器并發(fā)請(qǐng)求實(shí)現(xiàn)壓力性能測(cè)試,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-10-10mybatis(mybatis-plus)映射文件(XML文件)中特殊字符轉(zhuǎn)義的實(shí)現(xiàn)
XML 文件在解析時(shí)會(huì)將五種特殊字符進(jìn)行轉(zhuǎn)義,本文主要介紹了mybatis(mybatis-plus)映射文件(XML文件)中特殊字符轉(zhuǎn)義的實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下2023-12-12