Spring Cloud Gateway是spring cloud中起着非常重要的作用,是終端調用服務的入口,同時也是項目中每個服務對外暴露的統一口徑,我們可以在網關中實現路徑映射、權限驗證、負載均衡、服務聚合等業務功能。
(一) 版本說明
d) spring-cloud-starter-gateway 2.0.2.RELEASE
(二) 項目設置
1. Pom文件
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> <version>2.0.2.RELEASE</version> </dependency>
spring:
application:
name: gateway
cloud:
gateway:
enabled: true
routes:
#終端模塊
- id: clientservice
uri: lb://CLIENTSERVICE
predicates:
- Path=/client/**
filters:
- StripPrefix=1
#回調模塊
- id: callbackservice
uri: lb://CALLBACKSERVICE
predicates:
- Path=/callback/**
filters:
- StripPrefix=1
a) spring.application.name 項目名稱
b) spring.cloud.gateway 所有gateway配置信息的根節點
c) spring.cloud.gateway.enabled 是否啟用
d) spring.cloud.gateway.routes 路由映射,注意這里是數組
e) spring.cloud.gateway.routes[0].id 標志號
f) spring.cloud.gateway.routes[0].uri 路由映射目標路徑
g) spring.cloud.gateway.routes[0].predicates 匹配規則,也是暴露的映射路徑
h) spring.cloud.gateway.routes[0].StripPrefix 是否包含匹配的前綴,比如 /callback/**,如果設置為1,則只有**傳遞到目標路徑,如果設置為0,,則callback也一並傳遞到目標路徑,一般設置為1不傳遞自定義的暴露服務名稱
(三) 項目運行
1. 運行項目,在注冊中心即可看到gateway注冊進來了,如下圖所示
2. 也要把我們配置文件中配置的2個微服務已經在運行如下圖所示
名稱你可以改成你自己的服務名稱,但記得要跟配置的映射一致。
3. 在任何一個終端輸入gateway的IP:PORT/映射的服務名稱/API名稱,就可以看到經過網關映射后的效果
a) Client服務
b) Callback服務
這樣spring cloud gateway網關就介紹完了,如果在開發中遇到問題,也可以留言共同探討共同進步。