Sentinel 之 整合Gateway


Sentinel 從 1.6.0 版本開始,提供了 Spring Cloud Gateway 的適配模塊,可提供兩種資源維度的限流:

1、route  維度:在 Spring 配置 路由條目時,資源名為 routeId

2、自定義 API 維度,用戶可以用 Sentinel 提供的 API 來定義一些 API 分組

Gageway 模塊加入 Sentinel 整合依賴:

   <!-- Sentinel 配置 -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>
        <!--sentinel 整合 gateway-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
        </dependency>

<!-- 接入控制台的依賴 非必須,按需選擇使用 --> <dependency> <groupId>com.alibaba.csp</groupId> <artifactId>sentinel-transport-simple-http</artifactId> </dependency> <!-- Sentinel 持久化配置,支持多種持久化數據源:file、nacos、zookeeper、apollo、redis、consul 非必須,按需選擇,這里使用的是 Redis--> <dependency> <groupId>com.alibaba.csp</groupId> <artifactId>sentinel-datasource-redis</artifactId> </dependency>

 

自定義編寫一個配置類(通常不適用這種方式

@Component
public class GatewayConfiguration {
   @PostConstruct
   public void doInit() {
      //設置限流或降級的回調函數 new BlockRequestHandler() 匿名內部類
      GatewayCallbackManager.setBlockHandler((ServerWebExchange serverWebExchange, Throwable throwable) ->
            ServerResponse.status(200).bodyValue("系統繁忙請稍后"));
   }
}

在application.yml中配置sentinel控制台訪問地址(通常使用這種方式)
更過詳細配置請參看: https://gitee.com/chxlay/iserver-common/blob/master/iserver-common-sentinel/src/main/resources/application-sentinel.yml

# 官方文檔: https://sentinelguard.io/zh-cn/docs/dashboard.html
# 官方項目: https://github.com/alibaba/Sentinel/tree/master/sentinel-dashboard
# Sentinel 相關配置 Feign 的支持 配置信息可以遷移到 Nacos 中
spring:
  cloud:
    sentinel:
      transport:
        # 配置 Sentinel dashboard 地址信息
        dashboard: ${SENTINEL_HOST:iserver-sentinel}:${SENTINEL_PORT:8858}
        # Sentinel 默認端口號,加入被占用了,會自動從 8719 自動往后依次 +1 掃描,直到找到未占用的
        port: 8719
      scg:
      # 限流后的相應配置
        fallback:
          content-type: application/json
          # 模式: response / redirect
          mode: response
          # 相應狀態碼
          response-status: 200
          # 相應消息體
          response-body: '{"code":0,"message":"服務忙請稍后再試...","data":null}'
          # 請求重定向到某個地址
          redirect: https://www.iserver-cloud.com

 

啟動項目,在Sentinel控制台中添加關於資源的控制規則,sentinel在適配spring cloud gateway時提供了兩種配置規則

 

route維度:即在spring配置文件配置的路由條數,資源名為對應的routeId

自定義API維度:用戶可以利用Sentinel提供的API來自定義一些自定義分組

 

>>>>>>>>  接下一篇學習:https://www.cnblogs.com/Alay/p/15488126.html  <<<<<<<<<<<


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM