­

zuul集成Sentinel最新的網關流控組件

  • 2019 年 10 月 3 日
  • 筆記

一、說明

Sentinel 網關流控支援針對不同的路由和自定義的 API 分組進行流控,支援針對請求屬性(如 URL 參數,Client IP,Header 等)進行流控。Sentinel 1.6.3 引入了網關流控控制台的支援,用戶可以直接在 Sentinel 控制台上查看 API Gateway 實時的 route 和自定義 API 分組監控,管理網關規則和 API 分組配置。
file

 

二、功能接入

1. 網關添加sentinel相關的jar依賴

<dependency>      <groupId>com.alibaba.cloud</groupId>      <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>  </dependency>  <dependency>      <groupId>com.alibaba.csp</groupId>      <artifactId>sentinel-datasource-nacos</artifactId>  </dependency>  <dependency>      <groupId>com.alibaba.cloud</groupId>      <artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>  </dependency>

 

2. 網關zuul的sentinel配置

spring:    # sentinel動態配置規則    cloud:      sentinel:        zuul:          enabled: true          order:            pre: 2000            post: 500            error: -100        filter:          enabled: false        datasource:          # 限流          ds1:            nacos:              server-addr: ${zlt.nacos.server-addr}              dataId: ${spring.application.name}-sentinel-gw-flow              groupId: DEFAULT_GROUP              rule-type: gw-flow          # api分組          ds2:            nacos:              server-addr: ${zlt.nacos.server-addr}              dataId: ${spring.application.name}-sentinel-gw-api-group              groupId: DEFAULT_GROUP              rule-type: gw-api-group

綁定gw-flow(限流)gw-api-group(api分組)的規則數據源為nacos
並指定nacos上對應的dataIdgroupId

 

3. nacos規則配置

3.1. 限流配置gw-flow

file

  • Data ID:api-gateway-sentinel-gw-flow
  • Group:DEFAULT_GROUP
  • 配置內容:
[    {      "resource": "user",      "count": 0,      "paramItem": {        "parseStrategy": 3,        "fieldName": "name"      }    },    {      "resource": "uaa_api",      "count": 0    }  ]

規則1:所有user的請求只要參數帶有name的都攔截(qps=0),user為zuul路由配置上的routeId
規則2:api分組為uaa_api的所有請求都攔截(qps=0)

 

3.2. api分組配置gw-api-group

file

  • Data ID:api-gateway-sentinel-gw-api-group
  • Group:DEFAULT_GROUP
  • 配置內容:
[    {      "apiName": "uaa_api",      "predicateItems": [        {          "pattern": "/user/login"        },        {          "pattern": "/api-uaa/oauth/**",          "matchStrategy": 1        }      ]    }  ]

上面配置意思為滿足規則的api都統一分組為uaa_api
分組規則1:精準匹配/user/login
分組規則2:前綴匹配/api-uaa/oauth/**

 

4. 網關zuul啟動參數

需要在接入端原有啟動參數的基礎上添加-Dcsp.sentinel.app.type=1啟動以將您的服務標記為 API Gateway,在接入控制台時您的服務會自動註冊為網關類型,然後您即可在控制台配置網關規則和 API 分組,例如:

java -Dcsp.sentinel.app.type=1 -jar zuul-gateway.jar

 

三、sentinel控制台管理

API管理(分組)
file
網關流控規則
file

 

四、測試限流api

1. 測試限流規則1

所有user的請求只要參數帶有name的都攔截(qps=0)

  • 不加name參數,可以訪問api
    file
  • 後面加上name參數,請求被攔截
    file

 

2. 測試限流規則2

api分組為uaa_api的所有請求都攔截(qps=0)

  • 前綴匹配/api-uaa/oauth/**
    file
  • 精準匹配/user/login
    file