天天看點

Spring Boot(Cloud) 下整合 Sentinel 示例POM依賴AOP配置測試代碼@SentinelResource注解詳解

POM依賴

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>SentinelDemo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <sentinel.version>1.8.6</sentinel.version>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.11</version>
    </parent>

    <dependencies>
        <!--Sentinel核心依賴-->
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-core</artifactId>
            <version>${sentinel.version}</version>
        </dependency>
        <!--transport子產品,以支援Sentinel控制台-->
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-transport-simple-http</artifactId>
            <version>${sentinel.version}</version>
        </dependency>
        <!--提供sentinel注解支援子產品-->
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-annotation-aspectj</artifactId>
            <version>${sentinel.version}</version>
        </dependency>

        <!--以下是spring boot web的依賴-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- 添加web依賴 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

</project>
           
此處我們添加了transport子產品支援Sentinel控制台之間通信,添加了支援資源注解@SentinelResource的依賴。
Application啟動類和配置和Spring Boot 一樣,此處不再贅述。
注:如果是Spring Cloud Alibaba的項目,直接引入下面的start即可,上面Sentinel相關的依賴都可以不用加入
<dependency>
   <groupId>com.alibaba.cloud</groupId>
   <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
           

AOP配置

因為spring boot中使用了AOP,Sentinel的注解支援使用了Aspectj,是以需要添加如下配置

import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SentinelAspectConfiguration {

    @Bean
    public SentinelResourceAspect sentinelResourceAspect() {
        return new SentinelResourceAspect();
    }
}
           
注:此配置隻需要在Spring Boot下配置,如果你是使用的Spring Cloud Alibaba,此處可以跳過。

測試代碼

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("test")
public class FlowController {

    @PostConstruct
    public void initRole(){
        List<FlowRule> rules = new ArrayList<>(1);
        FlowRule rule = new FlowRule();
        // 設定規則比對的資源名稱
        rule.setResource("myFlowResource");
        // 規則作用類型(此為QPS類型,還有一種為FLOW_GRADE_THREAD,線程數類型)
        // 預設為QPS類型
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // 按Grade設定,此處為限制 QPS 為 2.
        rule.setCount(2);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }

    @RequestMapping("flow1")
    @SentinelResource(value = "myFlowResource",blockHandler = "block1")
    public Map<String,Object> flow1(){
        Map<String,Object> rs = new HashMap<>();

        rs.put("success",true);
        rs.put("msg","flow1通過流控正常傳回");
        return rs;
    }

    public Map<String,Object> block1(BlockException ex){
        Map<String,Object> rs = new HashMap<>();

        rs.put("success",false);
        rs.put("msg","flow1被流控");
        return rs;
    }

    @RequestMapping("flow2")
    @SentinelResource(value = "myFlowResource",blockHandler = "block2")
    public Map<String,Object> flow2(){
        Map<String,Object> rs = new HashMap<>();

        rs.put("success",true);
        rs.put("msg","flow2通過流控正常傳回");
        return rs;
    }

    public Map<String,Object> block2(BlockException ex){
        Map<String,Object> rs = new HashMap<>();

        rs.put("success",false);
        rs.put("msg","flow2被流控");
        return rs;
    }

}

           
此處為多元度驗證的代碼,我們在此一并解釋
  • @PostConstruct Spring的注解,辨別Bean的init方法。在Bean加載後執行。此處我們是為了在請求之前執行流控規則的代碼。
  • initRole方法,不用多說,定義了資源myFlowResource對應的流控規則,規則為QPS不超過2(設定為2是為了友善自我測試與驗證)。
  • flow1和flow2兩個接口,我們都定義為了同一個資源名稱。還記得我們上一篇文章介紹的嗎?
machine-root
                   /         \
                  /           \
          EntranceNode1   EntranceNode2
                /               \
               /                 \
       DefaultNode(nodeA)   DefaultNode(nodeA)
————————————————
https://blog.csdn.net/forlinkext/article/details/128917305
           
調用同一個資源nodeA,根據上下文的不同,是不同的調用樹。雖然可以對多段代碼配置同樣的資源名,但我們不建議這樣做。

@SentinelResource注解詳解

@SentinelResource 用于定義資源,并提供可選的異常處理和 fallback 配置項。 @SentinelResource 注解包含以下屬性:

  • value:資源名稱,必需項(不能為空)
  • entryType:entry 類型,可選項(預設為 EntryType.OUT)
  • blockHandler / blockHandlerClass: blockHandler 對應處理 BlockException 的函數名稱,可選項。
    • blockHandler 函數通路範圍需要是 public
    • 傳回類型需要與原方法相比對
    • 參數類型需要和原方法相比對并且最後加一個額外的參數,類型為 BlockException。
    • blockHandler 函數預設需要和原方法在同一個類中。若希望使用其他類的函數,則可以指定 blockHandlerClass 為對應的類的 Class 對象,注意對應的函數必需為 static 函數,否則無法解析。
  • fallback:fallback 函數名稱,可選項,用于在抛出異常的時候提供 fallback 處理邏輯。fallback 函數可以針對所有類型的異常(除了 exceptionsToIgnore 裡面排除掉的異常類型)進行處理。fallback 函數簽名和位置要求:
    • 傳回值類型必須與原函數傳回值類型一緻;
    • 方法參數清單需要和原函數一緻,或者可以額外多一個 Throwable 類型的參數用于接收對應的異常。
    • fallback 函數預設需要和原方法在同一個類中。若希望使用其他類的函數,則可以指定 fallbackClass 為對應的類的 Class 對象,注意對應的函數必需為 static 函數,否則無法解析。
  • defaultFallback(since 1.6.0):預設的 fallback 函數名稱,可選項,通常用于通用的 fallback 邏輯(即可以用于很多服務或方法)。預設 fallback 函數可以針對是以類型的異常(除了 exceptionsToIgnore 裡面排除掉的異常類型)進行處理。若同時配置了 fallback 和 defaultFallback,則隻有 fallback 會生效。defaultFallback 函數簽名要求:
    • 傳回值類型必須與原函數傳回值類型一緻;
    • 方法參數清單需要為空,或者可以額外多一個 Throwable 類型的參數用于接收對應的異常。
    • defaultFallback 函數預設需要和原方法在同一個類中。若希望使用其他類的函數,則可以指定 fallbackClass 為對應的類的 Class 對象,注意對應的函數必需為 static 函數,否則無法解析。
  • exceptionsToIgnore(since 1.6.0):用于指定哪些異常被排除掉,不會計入異常統計中,也不會進入 fallback 邏輯中,而是會原樣抛出。
注:若 blockHandler 和 fallback 都進行了配置,則被限流降級而抛出 BlockException 時隻會進入 blockHandler 處理邏輯。若未配置 blockHandler、fallback 和 defaultFallback,則被限流降級時會将 BlockException 直接抛出。
後續文章我們将以此文為基礎添加各種規則,還有比對Sentinel控制台等等。

繼續閱讀