網關Gateway斷⾔+過濾器整合注冊中心Nacos項目實戰
- 一、前言
- 二、網關介紹
- 三、基本網關轉發
-
- 1、建立Gateway項目
- 2、配置
- 四、整合注冊中心Nacos
-
- 1、添加Nacos依賴
- 2、啟動類開啟支援
- 3、修改配置檔案
- 4、網關通路的代碼
- 五、Gateway内置斷言實作接口定時下線與強制參數
-
- 六、SpringCloud+gateway+nacos整合踩過的坑
一、前言
提示:本文講到的代碼部分來自上文
上文連結位址
提示:以下是本篇文章正文内容,下面案例可供參考
二、網關介紹
API Gateway,是系統的唯一對外的入口,介于用戶端和伺服器端之間的中間層,處理非業務功能 提供路由請求、鑒權、監控、緩存、限流等功能
- 主流的網關
- zuul:是Netflix開源的微服務網關,和Eureka,Ribbon,Hystrix等元件配合使用,依賴元件比較多,性能教差
- kong: 由Mashape公司開源的,基于Nginx的API gateway
- nginx+lua:是一個高性能的HTTP和反向代理伺服器,lua是腳本語言,讓Nginx執行Lua腳本,并且高并發、非阻塞的處理各種請求
- springcloud gateway: Spring公司專門開發的網關,替代zuul
三、基本網關轉發
1、建立Gateway項目
添加依賴
<!--gateway依賴-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
2、配置
server:
port: 8888
spring:
application:
name: api-gateway
cloud:
gateway:
routes: #數組形式
- id: spring-other2 #路由唯一辨別,這裡自定義,一般是服務名
uri: http://127.0.0.1:9000 #想要轉發到的位址
order: 1 #優先級,數字越小優先級越高
predicates: #斷言 配置哪個路徑才轉發,前端轉發的字首路徑
- Path=/spring-other2/**
filters: #過濾器,請求在傳遞過程中通過過濾器修改
- StripPrefix=1 #去掉第一層字首(例如下面的spring-other2)
#通路路徑 http://localhost:8888/spring-other2/other2/getusername4?name=sb
#轉發路徑 http://localhost:9000/other2/getusername4?name=sb
#需要過濾器去掉前面第一層
效果圖
四、整合注冊中心Nacos
1、添加Nacos依賴
<!--添加nacos用戶端-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
2、啟動類開啟支援
3、修改配置檔案
server:
port: 8888
spring:
application:
name: api-gateway
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848 #nacos位址
gateway:
routes: #數組形式
- id: spring-other2 #路由唯一辨別,這裡自定義,一般是服務名
# uri: http://127.0.0.1:9000 #想要轉發到的位址
uri: lb://spring-other2 #想要轉發到的位址,從nacos轉發進行,後面跟服務名(lb負載均衡的意思)
order: 1 #優先級,數字越小優先級越高
predicates: #斷言 配置哪個路徑才轉發,前端轉發的字首路徑
- Path=/spring-other2/**
filters: #過濾器,請求在傳遞過程中通過過濾器修改
- StripPrefix=1 #去掉第一層字首(例如下面的spring-other2)
discovery:
locator:
enabled: true #開啟網關拉取nacos服務
#通路路徑 http://localhost:8888/spring-other2/other2/getusername4?name=sb
#轉發路徑 http://localhost:9000/other2/getusername4?name=sb
#需要過濾器去掉前面第一層
Gateway内置的路由斷言
predicates:
- Host=
- Path=
- Method=
- Header=
- Query=
- Cookie=
4、網關通路的代碼
@RestController
@RequestMapping("other2")
public class OtherController2 {
/**
* 測試gateway負載
* @return
*/
@RequestMapping("getusername8")
String getusername8( HttpServletRequest request) {
return "other2的getUserName7反回的資料-由"+request.getServerName()+":"+request.getServerPort()+"發起";
}
}
效果圖是一種預設輪詢
五、Gateway内置斷言實作接口定時下線與強制參數
- 需求:接口需要在指定時間進行下線,過後不可以在被通路
- 使用Before ,隻要目前時間小于設定時間,路由才會比對請求
- 東8區的2020-09-11T01:01:01.000+08:00後,請求不可通路
predicates:
- Before=2020-09-09T01:01:01.000+08:00
強制參數,如果沒有source參數則拒絕通路
predicates:
- Query=source
六、SpringCloud+gateway+nacos整合踩過的坑
path不能和服務名一樣,例如服務名為spring-other2則path可以叫api-spring-other2不能為spring-other2,否則routes配置無效
predicates:
- Path=