本篇文章只介紹gateway模塊的搭建步驟,并無gateway詳細介紹
gateway詳解請查看:SpringCloudGateway官方文檔詳解
前置處理
父模塊中已指定版本
不知道如何選擇版本看這篇:
手把手教你梳理springcloud與springboot與springcloudalibaba的版本對應關系
一. Gateway模塊引入依賴
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId>
</dependency><!--客戶端負載均衡loadbalancer-->
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
注意:gateway無需引入spring-boot-starter-web,因為gateway內部集成了Netty服務器,啟動會報錯
二. 配置 bootstrap.yml 文件(nacos作為注冊中心)
這里是引入nacos,gateway具體配置可以放在nacos配置中心
spring:application:name: gatewayprofiles:active: devcloud:nacos:username: nacospassword: nacosdiscovery:# 命名空間namespace: 26dc328e-87e1-4ebb-9882-e46aa0cfbf0c# 同一個項目下的服務,要在同一個分組下,相互間才能通信group: dev# nacos服務端server-addr: 127.0.0.1:8848config:# nacos服務端server-addr: 127.0.0.1:8848# 分組group: dev# 命名空間namespace: 26dc328e-87e1-4ebb-9882-e46aa0cfbf0c# 配置文件類型file-extension: yaml# 讀取公用配置shared-configs:- data-id: common-dev.yamlgroup: devrefresh: true
三. nacos配置中心中對應gateway配置文件
server:port: 7000spring:cloud:# 動態路由gateway:discovery:locator:# 開啟從注冊中心動態創建路由的功能,利用微服務名進行路由enabled: true# 表示將請求路徑的服務名配置改成小寫 ,因為服務注冊的時候,向注冊中心注冊時將服務名轉成大寫的了lowerCaseServiceId: true# 若配置路由URI為lb,則注冊中心服務名稱不能和server.servlet.context-path名稱一致,否則contextPath會被改寫為空字符串;加上這一行配置可以解決問題filters:- StripPrefix=0# 路線routes:- id: admin # 路線ID,保持唯一# 表示使用負載均衡策略,admin是服務IDuri: lb://admin# uri: http://localhost:7001# predicates定義了路由的匹配條件,這里使用的是路徑匹配,所有以/admin/開頭的請求都會被路由到admin服務。predicates:- Path=/admin/**- id: memberuri: lb://memberpredicates:- Path=/member/**- id: netdiskuri: lb://netdiskpredicates:- Path=/netdisk/**- id: bloguri: lb://blogpredicates:- Path=/blog/**- id: thirdpartyuri: lb://thirdpartypredicates:- Path=/thirdparty/**# 處理跨域請求globalcors:corsConfigurations:'[/**]':allowedHeaders: "*" # 允許所有請求頭allowedOriginPatterns: "*" # 允許所有請求源#- "http://www.baidu.com" # 允許特定請求源allowCredentials: true # 允許發送CookieallowedMethods: # 允許所有請求方法- GET- POST- DELETE- PUT- OPTION
四. 檢查gateway是否配置成功
還用這篇文章的測試接口 springcloud項目引入naocs2.x
admin模塊有一個測試接口,直接調用的連接為
http://localhost:7001/admin/nacos/getCommonNacosConfig
用gateway轉發的連接為
http://localhost:7000/admin/nacos/getCommonNacosConfig
五. 問題匯總
1. context-path和application.name一致問題:
若配置路由URI為lb,則注冊中心服務名稱不能和server.servlet.context-path名稱一致,否則contextPath會被改寫為空字符串;
解決方案:
- context-path和application.name設置為不同
- filters:
- StripPrefix=0
- filters[0]:
- StripPrefix=PreserveHostHeader
參考文章:https://blog.csdn.net/weixin_43303455/article/details/122279447
2. Whitelabel Error Page This application has no configured error view, so you are seeing this as a fallback.
原因是缺少負載均衡依賴
解決方法:gateway模塊引入spring-cloud-starter-loadbalancer依賴
<!--客戶端負載均衡loadbalancer-->
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>