天天看點

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

作者:小滿隻想睡覺

1、環境準備

1.1Nacos

單機啟動:startup.cmd -m standalone

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

1.2 Sentinel

啟動指令:java -Dserver.port=8858 -Dcsp.sentinel.dashboard.server=localhost:8858 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard-1.8.0.jar

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

1.3 JMeter

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

2、流控規則限流

2.0 環境搭建

2.0.1 依賴

<!--   nacos 依賴     -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

<!--   sentinel 流量防衛依賴    -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

<!--   暴露/actuator/sentinel端點 單獨配置,management開頭    -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
           

2.0.2 application.yml

# 端口
server:
  port: 9604

# 服務名
spring:
  application:
    name: kgcmall-sentinel

  # 資料源配置
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/kh96_alibaba_kgcmalldb?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
    username: root
    password: 17585273765

  # jpa配置
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true

  cloud:
    #nacos 配置
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848

    #sentinel 配置
    sentinel:
      transport:
        dashboard: 127.0.0.1:8858 # sentinel 控制台位址
        port: 9605 # 用戶端(核心應用)和控制台的通信端口,預設8719,子當以一個為被使用的唯一端口即可
      web-context-unify: false #關閉收斂 

# 暴露/actuator/sentinel端點 單獨配置,management 開頂格寫
management:
  endpoints:
    web:
      exposure:
        include: '*'
           

2.0.3 測試

http://localhost:9604/actuator/sentinel

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

2.1 流控模式

2.1.1 直接模式

2.1.1.1 測試請求

/**
* @param : [sentinelDesc]
* @return : java.lang.String
* @author : huayu
* @date : 26/11/2022
* @description : 測試 Sentinel 流控 - 直接失敗
*/
@GetMapping("testSentinelFlowFail")
public String testSentinelFlowFail(@RequestParam String sentinelDesc) {
    log.info("------ testSentinelFlowFail 接口調用 ------ ");
    return sentinelDesc;
}
           

2.1.1.2 添加直接流控規則

2.1.1.2.1 需要先發起異常請求

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

2.1.1.2.2 簇點鍊路 添加流控規則

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

2.1.1.2.3 設定流控規則

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

2.1.1.3檢視流控規則

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

2.1.1.4 測試

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

2.1.1.5 自定義sentinel統一已成傳回處理

/**
 * Created On : 26/11/2022.
 * <p>
 * Author : huayu
 * <p>
 * Description: 自定義sentinel統一已成傳回處理
 */
@Slf4j
@Component
public class MySentinelBlockExceptionHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        // 記錄異常日志
        log.warn("------ MySentinelBlockExceptionHandler 規則Rule:{} ------", e.getRule());

        // 增加自定義統一異常傳回對象
        RequestResult<String> requestResult = null;

        // 針對不同的流控異常,統一傳回
        if (e instanceof FlowException) {
            requestResult = ResultBuildUtil.fail("9621", "接口流量限流");
        } else if (e instanceof DegradeException) {
            requestResult = ResultBuildUtil.fail("9622", "接口服務降級");
        } else if (e instanceof ParamFlowException) {
            requestResult = ResultBuildUtil.fail("9623", "熱點參數限流");
        } else if (e instanceof SystemBlockException) {
            requestResult = ResultBuildUtil.fail("9624", "觸發系統保護");
        } else if (e instanceof AuthorityException) {
            requestResult = ResultBuildUtil.fail("9625", "授權規則限制");
        }

        // 統一傳回json結果
        httpServletResponse.setStatus(HttpStatus.FORBIDDEN.value());
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);

        // 借助SpringMVC自帶的Jackson工具,傳回結果
        new ObjectMapper().writeValue(httpServletResponse.getWriter(), requestResult);
    }


}
           

2.1.1.6 再次測試

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

2.1.2 關聯模式

2.1.2.1 測試請求

/**
* @param : [sentinelDesc]
* @return : java.lang.String
* @author : huayu
* @date : 26/11/2022
* @description : 測試 Sentinel 流控 - 關聯
*/
@GetMapping("testSentinelFlowLink")
public String testSentinelFlowLink(@RequestParam String sentinelDesc) {
    log.info("------ testSentinelFlowLink 接口調用 ------ ");
    return sentinelDesc;
}
           

2.1.1.2 添加關聯流控規則

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

2.1.1.3 JMeter壓測配置

2.1.1.3.1 線程組

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

2.1.1.3.2 Http請求

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

2.1.1.3.3 測試 testSentinelFlowLink 接口

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

2.1.3 鍊路模式

鍊路流控模式指的是,當從某個接口過來的資源達到限流條件時,開啟限流。它的功能有點類似于針對來源配置項,差別在于:針對來源是針對上級微服務,而鍊路流控是針對上級接口,也就是說它的粒度更細。

2.1.3.1 添加調用方法

2.1.3.1.1 接口

/**
 * Created On : 26/11/2022.
 * <p>
 * Author : huayu
 * <p>
 * Description: 測試鍊路 模式
 */
public interface SentinelService {

    void message();

}
           

2.1.3.1.2 實作類

/**
 * Created On : 26/11/2022.
 * <p>
 * Author : huayu
 * <p>
 * Description: 測試鍊路 模式 實作類
 */
@Service
public class SentinelServiceImpl implements SentinelService {

    @Override
    @SentinelResource("message") // 在@SentinelResource中指定資源名
    public void message() {
        System.out.println("message");
    }

}
           

2.1.3.2 兩個接口,調用相同的資源

@Slf4j
@RestController
public class KgcMallSentinelController {


    @Autowired
    private SentinelService sentinelService;

  //測試 Sentinel 流控 - 直接失敗
    @GetMapping("testSentinelFlowFail")
    public String testSentinelFlowFail(@RequestParam String sentinelDesc) {

        log.info("------ testSentinelFlowFail 接口調用 ------ ");

        //測試 鍊路模式調用相同的資源
        sentinelService.message();

        return sentinelDesc;
    }


    //測試 Sentinel 流控 - 關聯
    @GetMapping("testSentinelFlowLink")
    public String testSentinelFlowLink(@RequestParam String sentinelDesc) {

        log.info("------ testSentinelFlowLink 接口調用 ------ ");

        //測試 鍊路模式調用相同的資源
        sentinelService.message();
        return sentinelDesc;
    }

}
           

2.1.3.3 添加鍊路流控規則

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

2.1.3.4 測試

如果message觸發流控,指定的入口就會被限流;

2.1.3.4.0 高版本此功能直接使用不生效:

1.7.0 版本開始(對應SCA的2.1.1.RELEASE),官方在CommonFilter 引入了WEB_CONTEXT_UNIFY 參數,用于控制是否收斂context。将其配置為 false 即可根據不同的URL 進行鍊路限流。

spring:
  cloud:
    #sentinel 配置
    sentinel:
      web-context-unify: false #關閉收斂 
           

2.1.3.4.1 testSentinelFlowFail 請求

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

2.1.3.4.2 testSentinelFlowLink請求 (message 資源對此入口進行了限流)

使用鍊路規則,會導緻統一傳回處理,無法生效;

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

2.2 流控規則

2.2.1 快速失敗

快速失敗:直接抛出異常,預設的流量控制方式

當QPS超過任意規則的門檻值後,新的請求就會被立即拒絕。這種方式适用于對系統處理能力确切已知的情況下;

2.2.2 Warm Up(激增模式)

Warm Up(激增流量)即預熱/冷啟動方式;

冷加載因子: codeFactor 預設是3,即請求 QPS 從 1 / 3 開始,經預熱時長逐漸升至設定的 QPS 門檻值。

當系統長期處于低水位的情況下,當流量突然增加時,直接把系統拉升到高水位可能瞬間把系統壓垮。通過"冷啟動",讓通過的流量緩慢增加,在一定時間内逐漸增加到門檻值上限,給冷系統一個預熱的時間,避免冷系統被壓垮。

2.2.2.1 使用 testSentinelFlowFail 請求測試

請求方法省略;

2.2.2.2 流控配置

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

2.2.2.3 壓測配置

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

2.2.3.4 實時監控

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

2.2.3 勻速模式

會嚴格控制請求通過的間隔時間,也即是讓請求以均勻的速度通過,其餘的排隊等待,對應的是漏桶算法。

用于處理間隔性突發的流量,例如消息隊列,在某一秒有大量的請求到來,而接下來的幾秒則處于空閑狀态,這個時候我們不希望一下子把所有的請求都通過,這樣可能會把系統壓垮;同時我們也期待系統以穩定的速度,逐漸處理這些請求,以起到“削峰填谷”的效果,而不是第一秒拒絕所有請求。

選擇排隊等待的門檻值類型必須是QPS,且暫不支援>1000的模式

2.2.3.1 使用 testSentinelFlowFail 請求測試

請求方法省略;

單機門檻值:每秒通過的請求個數是5,則每隔200ms通過一次請求;每次請求的最大等待時間為500ms=0.5s,超過0.5S就丢棄請求。

2.2.3.2 流控配置

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

2.2.3.3 壓測配置

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

2.2.3.4 實時監控

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

3、降級規則限流

3.1慢調用比例-SLOW_REQUEST_RATIO

選擇以慢調用比例作為門檻值,需要設定允許的慢調用 RT(即最大的響應時間),請求的響應時間大于該值則統計為慢調用。當機關統計時長(statIntervalMs)内請求數目大于設定的最小請求數目,并且慢調用的比例大于門檻值,則接下來的熔斷時長内請求會自動被熔斷。經過熔斷時長後熔斷器會進入探測恢複狀态(HALF­OPEN 狀态),若接下來的一個請求響應時間小于設定的慢調用 RT 則結束熔斷,若大于設定的慢調用 RT 則會再次被熔斷。

3.1.1 模拟慢調用請求

/**
* @param : [sentinelDesc]
* @return : java.lang.String
 * @author : huayu
* @date : 26/11/2022
 * @description : 測試 Sentinel-降級-慢調用
*/
@GetMapping("testSentinelDown")
public String testSentinelDown(@RequestParam String sentinelDesc) throws InterruptedException {

    log.info("------ testSentinelDown 接口調用 ------ ");

    //模拟慢調用
    TimeUnit.MILLISECONDS.sleep(100);

    return sentinelDesc;
}
           

3.1.2 降級政策

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

3.1.3 壓測配置

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

3.1.4 實時監控

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

3.1.5 從浏覽器請求測試

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

3.2 異常比例-ERROR_RATIO

當機關統計時長(statIntervalMs)内請求數目大于設定的最小請求數目,并且異常的比例大于門檻值,則接下來的熔斷時長内請求會自動被熔斷。

經過熔斷時長後熔斷器會進入探測恢複狀态(HALF­OPEN 狀态),若接下來的一個請求成功完成(沒有錯誤)則結束熔斷,否則會再次被熔斷。異常比率的門檻值範圍是 [0.0, 1.0],代表 0% ­ 100%。

3.2.1 模拟異常比例請求

/**
* @param : [sentinelDesc]
* @return : java.lang.String
* @author : huayu
* @date : 26/11/2022
* @description : 測試 Sentinel-降級-異常比例    異常數
*/
@GetMapping("testSentinelDownExpScale")
public String testSentinelDownExpScale(@RequestParam String sentinelDesc) throws InterruptedException {

    log.info("------ testSentinelDownExpScale 接口調用 ------ ");

    //模拟異常
    int num = new Random().nextInt(10);
    if (num % 2 == 1) {
        num = 10 / 0;
    }
    return sentinelDesc;
}
           

3.2.2 降級政策

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

3.2.3 壓測配置

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

3.2.4 實時監控

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

3.2.5 從浏覽器請求測試

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

3.3 異常數-ERROR_COUNT

當機關統計時長内的異常數目超過門檻值之後會自動進行熔斷。經過熔斷時長後熔斷器會進入探測恢複狀态(HALF­OPEN 狀态),若接下來的一個請求成功完成(沒有錯誤)則結束熔斷,否則會再次被熔斷。

注意:異常降級僅針對業務異常,對 Sentinel 限流降級本身的異常(BlockException)不生效。

3.3.1 模拟異常參數請求

/**
* @param : [sentinelDesc]
* @return : java.lang.String
* @author : huayu
* @date : 26/11/2022
* @description : 測試 Sentinel-降級-異常比例    異常數
*/
@GetMapping("testSentinelDownExpScale")
public String testSentinelDownExpScale(@RequestParam String sentinelDesc) throws InterruptedException {

    log.info("------ testSentinelDownExpScale 接口調用 ------ ");

    //模拟異常
    int num = new Random().nextInt(10);
    if (num % 2 == 1) {
        num = 10 / 0;
    }
    return sentinelDesc;
}
           

3.3.2 降級政策

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

3.3.3 壓測配置

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

3.3.4 實時監控

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

3.3.5 從浏覽器請求測試

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

4、熱點規則限流

何為熱點?熱點即經常通路的資料。很多時候我們希望統計某個熱點資料中通路頻次最高的資料,并對其通路進行限制。

熱點參數限流會統計傳入參數中的熱點參數,并根據配置的限流門檻值與模式,對包含熱點參數的資源調用進行限流。熱點參數限流可以看做是一種特殊的流量控制,僅對包含熱點參數的資源調用生效

4.1 單機門檻值

單機門檻值:針對所有參數的值進行設定的一個公共的門檻值

  1. 假設目前參數大部分的值都是熱點流量,單機門檻值就是針對熱點流量進行設定,額外針對普通流量進行參數值流控;
  2. 假設目前參數大部分的值都是普通流量,單機門檻值就是針對普通流量進行設定,額外針對熱點流量進行參數值流控

配置熱點參數規則:

資源名必須是@SentinelResource(value="資源名")中 配置的資源名,熱點規則依賴于注解;

單獨指定參數例外的參數具體值,必須是指定的7種資料類型才會生效;

4.1.1 模拟 單機門檻值請求

/**
* @param : [sentinelDesc]
* @return : java.lang.String
* @author : huayu
* @date : 26/11/2022
* @description : 測試 Sentinel-熱點
*/
@GetMapping("testSentinelHotParam")
@SentinelResource(value = "sentinelHotParam", blockHandlerClass = MySentinelHotBlockExceptionHandler.class, blockHandler = "hotBlockExceptionHandle")
//熱點參數,必須使用此注解,指定資源名
//注意使用此注解無法處理BlockExecption,會導緻統一異常處理失效
public String testSentinelHotParam(@RequestParam String sentinelDesc) {

    log.info("------ testSentinelHotParam 接口調用 ------ ");

    return sentinelDesc;
}
           

4.1.2注意使用此注解無法處理BlockExecption,會導緻統一異常處理失效

4.1.2.1 方法一:類内處理方法

@GetMapping("testSentinelHotParam")
@SentinelResource(value = "sentinelHotParam",blockHandler = "hotBlockExceptionHandle")
//熱點參數,必須使用此注解,指定資源名
//注意使用此注解無法處理BlockExecption,會導緻統一異常處理失效
public String testSentinelHotParam(@RequestParam String sentinelDesc) {
    log.info("------ testSentinelHotParam 接口調用 ------ ");
    return sentinelDesc;
}



/**
* @author : huayu
* @date   : 26/11/2022
* @param  : [sentinelDesc, e]
* @return : java.lang.String
* @description : 類内處理方法  增加一個自定義處理方法,參數必須跟入口一緻
*/
public String hotBlockExceptionHandle(@RequestParam String sentinelDesc, BlockException e){
    //記錄異常日志
    log.warn("------ hotBlockExceptionHandle 規則Rule:{} ------", e.getRule());
    return JSON.toJSONString(ResultBuildUtil.fail("9623", "熱點參數限流")) ;

}
           

4.1.2.2 方法二:單獨處理類

@GetMapping("testSentinelHotParam")
@SentinelResource(value = "sentinelHotParam", blockHandlerClass = MySentinelHotBlockExceptionHandler.class, blockHandler = "hotBlockExceptionHandle")
//熱點參數,必須使用此注解,指定資源名
//注意使用此注解無法處理BlockExecption,會導緻統一異常處理失效
public String testSentinelHotParam(@RequestParam String sentinelDesc) {

    log.info("------ testSentinelHotParam 接口調用 ------ ");

    return sentinelDesc;
}


//==========處理類
/**
 * Created On : 26/11/2022.
 * <p>
 * Author : huayu
 * <p>
 * Description: 方式2 自定義熱點參數限流處理異常并指定治理方法
 */
@Slf4j
public class MySentinelHotBlockExceptionHandler {

    /**
     * @param : [sentinelDesc, e]
     * @return : java.lang.String
     * @author : huayu
     * @date : 26/11/2022
     * @description : hotBlockExceptionHandle  方法 必須是 靜态的  增加一個自定義處理方法,參數必須跟入口一緻
     */
    public static String hotBlockExceptionHandle(@RequestParam String sentinelDesc, BlockException e) {
        //記錄異常日志
        log.warn("------ hotBlockExceptionHandle 規則Rule:{} ------", e.getRule());
        return JSON.toJSONString(ResultBuildUtil.fail("9623", "熱點參數限流"));

    }


}
           

4.1.3 熱點參數政策和規則(sentinelHotParam)

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

4.1.4 浏覽器快速請求測試

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

5、授權規則限流

根據調用來源來判斷該次請求是否允許放行,這時候可以使用 Sentinel 的來源通路控制的功能。

來源通路控制根據資源的請求來源(origin)限制資源是否通過:

  • 若配置白名單,則隻有請求來源位于白名單内時才可通過;
  • 若配置黑名單,則請求來源位于黑名單時不通過,其餘的請求通過。

配置項:

  • 資源名resource,即限流規則的作用對象
  • 流控應用limitApp,對應的黑名單/白名單,不同 origin 用 , 分隔,如 appA,appBSentinel提供了 RequestOriginParser 接口來處理來源隻要Sentinel保護的接口資源被通路,Sentinel就會調用 RequestOriginParser 的實作類去解析通路來源。
  • 限制模式strategy,AUTHORITY_WHITE 為白名單模式,AUTHORITY_BLACK 為黑名單模式,預設為白名單模式

5.1 自定義來源處理規則

/**
 * Created On : 26/11/2022.
 * <p>
 * Author : huayu
 * <p>
 * Description: 自定義授權規則解析 來源 處理類
 */
@Component
public class MySentinelAuthRequestOriginParser implements RequestOriginParser {


    @Override
    public String parseOrigin(HttpServletRequest httpServletRequest) {

        // TODO 實際應用場景中,可以根據請求來源ip,進行ip限制
        //模拟,通過請求參數中,是否攜帶了自定義的來源參數OriginAuth
        //根據授權規則中的流控應用規則指定的參數清單,限制是否可以通路
        //授權規則,指定白名單,就代表請求攜帶的參數OriginAuth,參數值必須是在流控應用指定的參數清單中,才可以通路,否者不允許
        //黑名單相反
        return httpServletRequest.getParameter("originAuth");
    }


}
           

5.2 模拟授權請求

/**
* @param : [sentinelDesc]
* @return : java.lang.String
* @author : huayu
* @date : 26/11/2022
* @description : 測試 Sentinel-授權
*/
@GetMapping("testSentinelAuth")
public String testSentinelAuth(@RequestParam String sentinelDesc,
                               @RequestParam String originAuth) {

    log.info("------ testSentinelHotParam 接口調用 ------ ");

    return "sentinelDesc:" + sentinelDesc + "\n,originAuth:" + originAuth;
}
           

5.3 白名單

5.3.1 配置白名單

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

5.3.2 測試

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

5.4黑名單

5.4.1 配置黑名單

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

5.4.2 測試

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

6、系統規則限流

系統保護規則是從應用級别的入口流量進行控制,從單台機器的總體 Load、RT、入口 QPS 、CPU使用

率和線程數五個次元監控應用資料,讓系統盡可能跑在最大吞吐量的同時保證系統整體的穩定性。系統

保護規則是應用整體次元的,而不是資源次元的,并且僅對入口流量 (進入應用的流量) 生效。

  • Load 自适應(僅對 Linux/Unix­like 機器生效):系統的 load1 作為啟發名額,進行自适應系統保護。當系統load1 超過設定的啟發值,且系統目前的并發線程數超過估算的系統容量時才會觸發系統保護。系統容量由系統的 maxQps * minRt 估算得出。設定參考值一般是 CPU cores * 2.5。
  • CPU usage(1.5.0+ 版本):當系統 CPU 使用率超過門檻值即觸發系統保護(取值範圍 0.0­ - 1.0),比較靈敏。
  • 平均 RT:當單台機器上所有入口流量的平均 RT 達到門檻值即觸發系統保護,機關是毫秒。
  • 并發線程數:當單台機器上所有入口流量的并發線程數達到門檻值即觸發系統保護。
  • 入口 QPS:當單台機器上所有入口流量的 QPS 達到門檻值即觸發系統保護

6.1 模拟系統限流請求

/**
* @param : [sentinelDesc]
* @return : java.lang.String
* @author : huayu
* @date : 26/11/2022
* @description : 測試 Sentinel-系統
* //設定一個, 全部請求都受限制
*/
@GetMapping("testSentinelSys")
public String testSentinelSys(@RequestParam String sentinelDesc) {

    log.info("------ testSentinelHotParam 接口調用 ------ ");

    return "sentinelDesc:" + sentinelDesc;
}
           

6.2 系統規則配置

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

6.3 壓測配置

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

6.4 浏覽器測試

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

7、Sentinel 規則持久化

Dashboard控制台來為每個Sentinel用戶端設定各種各樣的規則,但是這裡有一個問題,就是這些規則預設是存放在記憶體中,每次微服務重新啟動,設定的各種規則都會消失。

7.1 方式1:本地檔案(測試,線上不推薦)

本地檔案資料源會定時輪詢檔案的變更,讀取規則。這樣我們既可以在應用本地直接修改檔案來更新規則,也可以通過 Sentinel 控制台推送規則。

原理:首先 Sentinel 控制台通過 API 将規則推送至用戶端并更新到記憶體中,接着注冊的寫資料源會将新的規則儲存到本地的檔案中。

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

7.1.1 配置類

建立配置類: SentinelFilePersistence

import com.alibaba.csp.sentinel.command.handler.ModifyParamFlowRulesCommandHandler;
import com.alibaba.csp.sentinel.datasource.*;
import com.alibaba.csp.sentinel.init.InitFunc;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRuleManager;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager;
import com.alibaba.csp.sentinel.slots.system.SystemRule;
import com.alibaba.csp.sentinel.slots.system.SystemRuleManager;
import com.alibaba.csp.sentinel.transport.util.WritableDataSourceRegistry;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * Created On : 26/11/2022.
 * <p>
 * Author : huayu
 * <p>
 * Description: MySentinelRulePersistenceDunc
 */
public class MySentinelRulePersistencefunc implements InitFunc{

//    String ruleDir = System.getProperty("user.home") + "/sentinel/rules/";
    //填寫 規則存放的絕對路徑
    String ruleDir = "D:/KEGONGCHANG/DaiMa/IDEA/KH96/SpringCloud/springcloud-alibaba-96/kgcmall96-sentinel/sentinel/rules/";
//    String ruleDir = "/kgcmall96-sentinel/sentinel/rules/";

    String flowRulePath = ruleDir + "/flow-rule.json";
    String degradeRulePath = ruleDir + "/degrade-rule.json";
    String systemRulePath = ruleDir + "/system-rule.json";
    String authorityRulePath = ruleDir + "/authority-rule.json";
    String paramFlowRulePath = ruleDir + "/param-flow-rule.json";

    @Override
    public void init() throws Exception {

        // 建立規則存放目錄
        this.mkdirIfNotExits(ruleDir);

        // 建立規則存放檔案
        this.createFileIfNotExits(flowRulePath);
        this.createFileIfNotExits(degradeRulePath);
        this.createFileIfNotExits(systemRulePath);
        this.createFileIfNotExits(authorityRulePath);
        this.createFileIfNotExits(paramFlowRulePath);


        // 注冊一個可讀資料源,用來定時讀取本地的json檔案,更新到規則緩存中
        // 流控規則
        ReadableDataSource<String, List<FlowRule>> flowRuleRDS =
                new FileRefreshableDataSource<>(flowRulePath, flowRuleListParser);

        // 将可讀資料源注冊至FlowRuleManager,這樣當規則檔案發生變化時,就會更新規則到記憶體
        FlowRuleManager.register2Property(flowRuleRDS.getProperty());
        WritableDataSource<List<FlowRule>> flowRuleWDS = new FileWritableDataSource<>(
                flowRulePath,
                this::encodeJson
        );

        // 将可寫資料源注冊至transport子產品的WritableDataSourceRegistry中
        // 這樣收到控制台推送的規則時,Sentinel會先更新到記憶體,然後将規則寫入到檔案中
        WritableDataSourceRegistry.registerFlowDataSource(flowRuleWDS);

        // 降級規則
        ReadableDataSource<String, List<DegradeRule>> degradeRuleRDS = new FileRefreshableDataSource<>(
                degradeRulePath,
                degradeRuleListParser
        );
        DegradeRuleManager.register2Property(degradeRuleRDS.getProperty());
        WritableDataSource<List<DegradeRule>> degradeRuleWDS = new FileWritableDataSource<>(
                degradeRulePath,
                this::encodeJson
        );
        WritableDataSourceRegistry.registerDegradeDataSource(degradeRuleWDS);

        // 系統規則
        ReadableDataSource<String, List<SystemRule>> systemRuleRDS = new FileRefreshableDataSource<>(
                systemRulePath,
                systemRuleListParser
        );
        SystemRuleManager.register2Property(systemRuleRDS.getProperty());
        WritableDataSource<List<SystemRule>> systemRuleWDS = new FileWritableDataSource<>(
                systemRulePath,
                this::encodeJson
        );
        WritableDataSourceRegistry.registerSystemDataSource(systemRuleWDS);

        // 授權規則
        ReadableDataSource<String, List<AuthorityRule>> authorityRuleRDS = new FileRefreshableDataSource<>(
                authorityRulePath,
                authorityRuleListParser
        );
        AuthorityRuleManager.register2Property(authorityRuleRDS.getProperty());
        WritableDataSource<List<AuthorityRule>> authorityRuleWDS = new FileWritableDataSource<>(
                authorityRulePath,
                this::encodeJson
        );
        WritableDataSourceRegistry.registerAuthorityDataSource(authorityRuleWDS);

        // 熱點參數規則
        ReadableDataSource<String, List<ParamFlowRule>> paramFlowRuleRDS = new FileRefreshableDataSource<>(
                paramFlowRulePath,
                paramFlowRuleListParser
        );
        ParamFlowRuleManager.register2Property(paramFlowRuleRDS.getProperty());
        WritableDataSource<List<ParamFlowRule>> paramFlowRuleWDS = new FileWritableDataSource<>(
                paramFlowRulePath,
                this::encodeJson
        );
        ModifyParamFlowRulesCommandHandler.setWritableDataSource(paramFlowRuleWDS);

    }

        private Converter<String, List<FlowRule>> flowRuleListParser = source -> JSON.parseObject(
                source,
                new TypeReference<List<FlowRule>>() {
                }
        );
        private Converter<String, List<DegradeRule>> degradeRuleListParser = source -> JSON.parseObject(
                source,
                new TypeReference<List<DegradeRule>>() {
                }
        );
        private Converter<String, List<SystemRule>> systemRuleListParser = source -> JSON.parseObject(
                source,
                new TypeReference<List<SystemRule>>() {
                }
        );

        private Converter<String, List<AuthorityRule>> authorityRuleListParser = source -> JSON.parseObject(
                source,
                new TypeReference<List<AuthorityRule>>() {
                }
        );

        private Converter<String, List<ParamFlowRule>> paramFlowRuleListParser = source -> JSON.parseObject(
                source,
                new TypeReference<List<ParamFlowRule>>() {
                }
        );

        private void mkdirIfNotExits(String filePath) throws IOException {
            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
        }

        private void createFileIfNotExits(String filePath) throws IOException {
            File file = new File(filePath);
            if (!file.exists()) {
                file.createNewFile();
            }
        }

        private <T> String encodeJson(T t) {
            return JSON.toJSONString(t);
        }

}

           

7.1.2 InitFunc 檔案

在resources檔案下建立META-INF/services檔案夾;

建立文檔com.alibaba.csp.sentinel.init.InitFunc,文檔名就是配置類實作接口的全類名;

在檔案中添加第一步配置類的全類名即可;

測試:啟動服務,當通路系統規則限流接口,自動建立目錄和檔案,添加規則後,重新開機服務,剛進來,之前的配置看不到,必須先通路對應的入口才可以,要注意

com.kgc.scda.config.MySentinelRulePersistencefunc
           

8、Openfeign 遠端調用

8.1 依賴

<!--    openfeign 遠端調用    -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
    <version>2.1.1.RELEASE</version>
</dependency>
           

8.2 配置

# 整合Sentinel 和OpenFeign ,預設關閉
feign:
  sentinel:
    enabled: true  #開啟
           

8.3 注解

著啟動類: @EnableFeignClients

接口:@FeignClient(value = "服務名")
           

8.4 測試 (與單獨使用Openfeign一樣不在贅述)

9、GateWay 服務網關

9.1 依賴

<!--  Gatway 網關會和springMvc沖突,不能添加web依賴      -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>

<!--   gateway 依賴     -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
           

9.2 配置

# 端口
server:
  port: 9606

# 服務名
spring:
  application:
    name: kgcmall-gatway

  cloud:
    #nacos 配置
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848

    # 網關配置
    gateway:
      routes: # 路由,是list集合,可以配置多個路由
      	#product子產品
        - id: kh96_route_first # 目前route路由的唯一辨別,不能重複
          #uri: http://localhost:9602 # 路由轉發的目标資源位址,不支援多負載調用,不利于擴充,不推薦
          uri: lb://kgcmall96-prod # lb 從nacos注冊中心的服務清單中,根據指定的服務名,調用服務,推薦用法
          predicates: # 指定路由斷言配置,支援多個斷言,隻要斷言成功(滿足路由轉發條件),才會執行轉發到目标資源位址通路
            - Path=/prod-gateway/** # 指定path路徑斷言,必須滿足請求位址是/prod-gateway開始,才會執行路由轉發
          filters: # 指定路由過濾配置,支援多個過濾器,在斷言成功,執行路由轉發時,對請求和響應資料進行過濾處理
            - StripPrefix=1 # 在請求斷言成功後,執行路由轉發時,自動去除第一層的通路路徑/prod-gateway
        #user子產品
        - id: kh96_route_second
          uri: lb://kgcmall96-user
          predicates:
            - Path=/user-gateway/**
          filters:
            - StripPrefix=1
           

9.3 測試

9.3.1 nacos

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

9.3.2 請求測試

9.3.2.1 通過gateway網關調用prod子產品

SpringCloud Alibaba整合OpenFeign,GateWay服務網關

9.3.2.1 通過gateway網關調用user子產品

SpringCloud Alibaba整合OpenFeign,GateWay服務網關