1. 概述
老話說的好:做人要有幽默感,懂得幽默的人才會活的更開心。
言歸正傳,今天我們來聊聊 SpringCloud 的網關元件 Gateway,之前我們去通路 SpringCloud 不同服務的接口,都要去找每個服務的 IP位址 和 端口,有了 Gateway 這個元件,我們就可以從一個入口,去通路所有在 Eureka 中注冊的服務。
閑話不多說,直接上代碼。
2. Gateway 工程的搭建
2.1 主要依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
2.2 application.yml 主要配置
server:
port: 44000
spring:
application:
name: my-gateway
cloud:
gateway:
discovery:
locator:
enabled: true
eureka:
client:
service-url:
defaultZone: http://zhuifengren1:35000/eureka/,http://zhuifengren2:35001/eureka/ # Eureka Server的位址
management:
endpoints:
web:
exposure:
include: '*'
endpoint:
health:
show-details: always
2.3 啟動類注解
@SpringBootApplication
@EnableDiscoveryClient
public class MyGateWayApplication {
public static void main(String[] args) {
SpringApplication.run(MyGateWayApplication.class, args);
}
}
2.4 啟動 Gateway 服務,并通路測試
1)啟動 Eureka 服務
2)啟動之前章節中講到的 my-eureka-client 服務
3)啟動 Gateway 服務
4)通過 Gateway 服務調用 my-eureka-client 服務暴露的接口
接口位址:http://localhost:44000/MY-EUREKA-CLIENT/eurekaClient/hello
位址格式:http://Gateway服務IP:端口/服務名大寫/請求路徑
2.5 位址中服務名改為小寫
剛剛的實驗中,我們發現,通過 Gateway 通路服務接口,服務的名稱必須寫為大寫,才能正确通路接口,有點不習慣,我們可以通過配置将其統一改為小寫。
增加如下配置即可:
cloud:
gateway:
discovery:
locator:
enabled: true
lower-case-service-id: true # service-id 是否用小寫
3. 自定義動态路由
3.1 概述
有時我們不想用服務名當做接口的字首,可以自定義動态路由。
3.2 增加動态路由
POST http://localhost:44000/actuator/gateway/routes/myroute
最後的 myroute 是自定義路由的 ID,保證唯一即可。
參數:
{
"predicates": [
{
"name":"Path",
"args":{
"_genkey_0":"/myroute/**"
}
}
],
"filters": [
{
"name":"StripPrefix",
"args":{
"_genkey_0":"1"
}
}
],
"uri": "lb://MY-EUREKA-CLIENT",
"order": 0
}
參數的含義是,所有以 myroute 開頭的URL,統一轉發到 MY-EUREKA-CLIENT 服務。
3.3 使用動态路由通路接口
http://localhost:44000/myroute/eurekaClient/hello
3.4 删除動态路由
DELETE http://localhost:44000/actuator/gateway/routes/myroute
4. 綜述
今天聊了一下 SpringCloud 的 Gateway 元件,希望可以對大家的工作有所幫助。
歡迎幫忙點贊、評論、轉發、加關注 :)
關注追風人聊Java,每天更新Java幹貨。
5. 個人公衆号
追風人聊Java,歡迎大家關注
