1. 程式人生 > 實用技巧 >Spring Cloud Alibaba:Sentinel初始化監控和流控

Spring Cloud Alibaba:Sentinel初始化監控和流控

sentinel介紹

隨著微服務的流行,服務和服務之間的穩定性變得越來越重要。Sentinel 以流量為切入點,從流量控制、熔斷降級、系統負載保護等多個維度保護服務的穩定性。
Sentinel 具有以下特徵:
豐富的應用場景:Sentinel 承接了阿里巴巴近 10 年的雙十一大促流量的核心場景,例如秒殺(即突發流量控制在系統容量可以承受的範圍)、訊息削峰填谷、叢集流量控制、實時熔斷下游不可用應用等。
完備的實時監控:Sentinel 同時提供實時的監控功能。您可以在控制檯中看到接入應用的單臺機器秒級資料,甚至 500 臺以下規模的叢集的彙總執行情況。
廣泛的開源生態:Sentinel 提供開箱即用的與其它開源框架/庫的整合模組,例如與 Spring Cloud、Dubbo、gRPC 的整合。您只需要引入相應的依賴並進行簡單的配置即可快速地接入 Sentinel。
完善的 SPI 擴充套件點:Sentinel 提供簡單易用、完善的 SPI 擴充套件介面。您可以通過實現擴充套件介面來快速地定製邏輯。例如定製規則管理、適配動態資料來源等。
sentinel主要特性:

安裝

docker pull bladex/sentinel-dashboard
docker run --name sentinel -d -p 8858:8858 -d bladex/sentinel-dashboard

訪問:192.168.10.137:8858,賬號密碼預設sentinel,進入控制檯

pom依賴

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <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>

配置檔案yml

server:
  port: 8401
spring:
  application:
    name: cloudalibaba-sentinel-service
  cloud:
    nacos:
      discovery:
        #nacos服務註冊中心地址
        server-addr: 192.168.10.137:8848
    sentinel:
      transport:
        #sentinel dashboard地址
        dashboard: 192.168.10.137:8858
        #預設8719埠,假如被佔用會自動從8719開始依次掃描,直到找到未被佔用的埠
        port: 8719
management:
  endpoints:
    web:
      exposure:
        include: '*'

controller

@RestController
public class FlowLimitController {
    @GetMapping("/testA")
    public String testA() throws InterruptedException {
        TimeUnit.SECONDS.sleep(1);
        return "testA";
    }
}

啟動服務,訪問controller,再觀察sentinel的結果

流控

qps流控

新增一個qps流控規則(每秒的請求數量)

當快速訪問介面時,訪問失敗。

執行緒數流控

當執行緒數達到閾值的時候限流,例如我設定執行緒數的閾值為1(同時有且只有一個執行緒能訪問該介面)

關聯

當關聯的資源達到閾值的時候,就限流自己。
例如A關聯的資源B達到了閾值後,就限流自己。

鏈路

多個請求呼叫同一個微服務