初探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)目提供簡單高效的API路由,以及強(qiáng)大的擴(kuò)展能力:安全、監(jiān)控、彈性計(jì)算等
- 官方架構(gòu)圖如下,可見請求到來后,由Handler Mapping決定請求對應(yīng)的真實(shí)目標(biāo),然后交給Web Handler,由一系列過濾器(filter)執(zhí)行鏈?zhǔn)教幚?,從紅色箭頭和注釋可以發(fā)現(xiàn),請求前后都有過濾器在運(yùn)行:

版本信息
- 《Spring Cloud Gateway實(shí)戰(zhàn)》系列涉及的軟件和庫版本信息如下:
- 本篇實(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)典配置中的核心概念
- 先通過一個(gè)典型的簡化版配置來了解幾個(gè)核心概念,假設(shè)Spring Cloud Gateway應(yīng)用正在運(yùn)行,監(jiān)聽8080端口,一旦有遠(yuǎn)程請求來到8080端口,下面的配置就會(huì)生效了,三個(gè)核心概念,以及每個(gè)配置的作用,請參考中文注釋:
spring:
cloud:
gateway:
# 核心概念1:路由,一個(gè)路由代表一個(gè)處理邏輯,
# 該邏輯里面包含三個(gè)元素:匹配條件(是否該此路由處理)、真實(shí)處理地址、過濾器
routes:
# id要確保唯一性
- id: add_request_header_route
# 真實(shí)處理地址,請求一旦確定是當(dāng)前路由處理,就會(huì)轉(zhuǎn)發(fā)到這個(gè)地址去
uri: https://example.org
# 核心概念2:謂語或者斷言,作用是判斷請求是否由當(dāng)前路由處理
predicates:
# 這是斷言的一種,檢查請求的Cookie中mycookie的值是否等于mycookievalue
- Cookie=mycookie,mycookievalue
# 核心概念3:過濾器,請求前和請求后都可以有過濾器處理請求響應(yīng)數(shù)據(jù)
filters:
# 這個(gè)過濾器的作用是在請求header中添加一個(gè)鍵值對,值等于"aaabbbccc"
- AddRequestHeader=X-Request-Red, aaabbbccc
- 上述配置信息中的predicates是簡化版配置,和完整配置對比效果如下,簡單的說就是把一行拆成了三項(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ì)用到注冊中心和配置中心,這里我選擇了nacos,它可以很好地承擔(dān)注冊中心和配置中心的角色,接下來介紹如何部署和啟動(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,請執(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):
| 名稱 | 鏈接 | 備注 |
|---|---|---|
| 項(xiàng)目主頁 | https://github.com/zq2599/blog_demos | 該項(xiàng)目在GitHub上的主頁 |
| git倉庫地址(https) | https://github.com/zq2599/blog_demos.git | 該項(xiàng)目源碼的倉庫地址,https協(xié)議 |
| git倉庫地址(ssh) | git@github.com:zq2599/blog_demos.git | 該項(xiàng)目源碼的倉庫地址,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)容如下,可見這里將springboot、spring-cloud、spring-cloud-alibaba庫的版本號(hào)都已經(jīng)確定,今后子工程就無需關(guān)注依賴庫的版本號(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ù),咱們在嘗試Spring Cloud Gateway的基本功能時(shí),都會(huì)將請求路由到provider-hello上來
- provider-hello是個(gè)普通的springboot應(yīng)用,會(huì)在nacos進(jìn)行注冊,其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ù)注冊與發(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)類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類Hello.java,對外提供一個(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());
}
/**
* 返回字符串類型
* @return
*/
@GetMapping("/str")
public String helloStr() {
return Constants.HELLO_PREFIX + ", " + dateStr();
}
}
新增測試類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í)行單元測試(此時(shí)nacos是否啟動(dòng)無所謂,只是不啟動(dòng)的話控制臺(tái)會(huì)有一些錯(cuò)誤信息,但是沒有影響),如下,測試通過表示服務(wù)是正常的:

開發(fā)一個(gè)簡單的demo,完成spring-cloud-gateway的初體驗(yàn)
- 前面做了那么多準(zhǔn)備,接下來咱們會(huì)投入到Spring Cloud Gateway的開發(fā)中,先寫個(gè)簡單的demo快速體驗(yàn)一下
- 新增名為hello-gateway的子工程,pom.xml如下,重點(diǎn)是依賴了spring-cloud-starter-gateway庫,還有一處要重點(diǎn)小心的:測試庫用的是reactor-test和spring-boot-starter-test,這和之前的單元測試很不一樣,用的是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ì)直接使用原始請求的
# 例如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ù)請求路徑中帶有"/hello/",就算匹配成功
- Path=/hello/**
如果要轉(zhuǎn)發(fā)到其他域名下,需要?jiǎng)?chuàng)建配置類解決跨域問題:
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)類:
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);
}
}
- 最后是單元測試類,請注意,由于Spring Cloud Gateway使用了webflux技術(shù)棧,因此不能用常見的MockMvc來模擬請求,幾個(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)));
}
}
請確保provider-hello應(yīng)用已經(jīng)啟動(dòng),再運(yùn)行上面創(chuàng)建的HelloTest.java,得到結(jié)果如下,測試通過,證明hello-gateway的功能符合預(yù)期,成功的將請求轉(zhuǎn)發(fā)到provider-hello應(yīng)用,并且成功收到響應(yīng):

至此,《Spring Cloud Gateway實(shí)戰(zhàn)》系列的準(zhǔn)備工作已經(jīng)完成,而且開發(fā)了一個(gè)簡單的應(yīng)用體驗(yàn)最基本的Spring Cloud Gateway功能,接下來的文章,咱們一起實(shí)戰(zhàn)更多基本功能。
總結(jié)
本篇文章就到這里了,希望能給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
Spring學(xué)習(xí)之動(dòng)態(tài)代理(JDK動(dòng)態(tài)代理和CGLIB動(dòng)態(tài)代理)
本篇文章主要介紹了Spring學(xué)習(xí)之動(dòng)態(tài)代理(JDK動(dòng)態(tài)代理和CGLIB動(dòng)態(tài)代理),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-07-07
Java8中Optional操作的實(shí)際應(yīng)用
Optional類是一個(gè)可以為null的容器對象,如果值存在則isPresent()方法會(huì)返回true,調(diào)用get()方法會(huì)返回該對象,下面這篇文章主要給大家介紹了關(guān)于Java8中Optional操作實(shí)際應(yīng)用的相關(guān)資料,需要的朋友可以參考下2022-02-02
后端報(bào)TypeError:Cannot?read?properties?of?null?(reading?‘
這篇文章主要給大家介紹了關(guān)于后端報(bào)TypeError:Cannot?read?properties?of?null?(reading?‘xxx‘)錯(cuò)誤的解決辦法,這個(gè)錯(cuò)誤是開發(fā)中常見的錯(cuò)誤之一,需要的朋友可以參考下2023-05-05
HashMap方法之Map.getOrDefault()解讀及案例
這篇文章主要介紹了HashMap方法之Map.getOrDefault()解讀及案例,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03
Java對象在內(nèi)存中的布局是如何實(shí)現(xiàn)的?
Java對象在內(nèi)存中屬于oop-klass二分模型,即對象的實(shí)例數(shù)據(jù)和對象類型的元數(shù)據(jù)(字段定義、方法、常量池等元數(shù)據(jù))是分開存儲(chǔ)的.而由于JVM對對象內(nèi)相同寬度的字段分配在一起,所以只要指定了字段類型分配的順序,就可以計(jì)算出每種類型字段相對于當(dāng)前對象的偏移起始位置2021-06-06
java通過snmp協(xié)議獲取物理設(shè)備信息
這篇文章主要介紹了java通過snmp協(xié)議獲取物理設(shè)備信息,snmp中文含義是簡單網(wǎng)絡(luò)管理協(xié)議,可用完成對計(jì)算機(jī)、路由器和其他網(wǎng)絡(luò)設(shè)備的遠(yuǎn)程管理和監(jiān)視,本文我們是通過java程序來獲取,需要的朋友可以參考下2023-07-07
如何在SpringBoot項(xiàng)目中使用Oracle11g數(shù)據(jù)庫
這篇文章主要介紹了在SpringBoot項(xiàng)目中使用Oracle11g數(shù)據(jù)庫的操作,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06

