Spring Cloud Alibaba 隨記

官方項目文檔

https://github.com/alibaba/spring-cloud-alibaba/blob/master/README-zh.md

測試項目

https://gitee.com/sw008/SpringCloudAlibaba_test/tree/master

Nacos

1 控制檯地址在Nacos-server(github下載)啓動時會暴露。

2 在控制檯可以控制服務下線/上線/權重,但是會有延遲。因爲客戶端在下次同步服務列表時纔會感知。

 

Sentinel

官方文檔:

https://github.com/alibaba/spring-cloud-alibaba/wiki/Sentinel

https://github.com/alibaba/Sentinel/wiki/如何使用

Sentinel可以爲"/hello"或"re"做流控配置

1 舊版本BUG

@RequestMapping("/hello")
public String sayHello(){
   //直接調用方法aop失效 
   return doHello();
}

//AOP實現
@SentinelResource("re")
public String doHello(){
   return "hello";
}

2 @SentinelResource降級熔斷

官方文檔:https://github.com/alibaba/Sentinel/wiki/%E6%B3%A8%E8%A7%A3%E6%94%AF%E6%8C%81

https://blog.csdn.net/a772304419/article/details/99689562

Sentinel控制檯

啓動

(官方github下載)

  1. 首先需要獲取 Sentinel 控制檯,支持直接下載和源碼構建兩種方式。

    1. 直接下載:下載 Sentinel 控制檯
    2. 源碼構建:進入 Sentinel Github 項目頁面,將代碼 git clone 到本地自行編譯打包,參考此文檔
  2. 啓動控制檯,執行 Java 命令 java -jar sentinel-dashboard.jar完成 Sentinel 控制檯的啓動。 控制檯默認的監聽端口爲 8080。

若下載官方編譯好的sentinel-dashboard.jar啓動報錯,則需要git clone sentinel項目,找到sentinel-dashboard子模塊(springboot)運行main()方法啓動。

配置

1、每次設置規則只對同名服務集羣中一臺機器的資源生效。同樣的服務可以爲不同進程配置不同規則。 

2、上圖中左側是服務列表,點擊一個服務名可以看到監控+鏈路+規則等選項。

3、上圖中顯示demo-consumer服務中一臺服務實例/進程的請求情況。QPS等信息只記錄短時間過期重置爲0。

      上圖中標出各個鏈路對應demo-consumer中的信息。測試代碼:https://gitee.com/sw008/SpringCloudAlibaba_test/tree/master/demo-consumer

4、爲對應的資源配置流量、降級、熱點、授權規則。

流控:超過標準會拋出FlowException

注意:如上圖有多個URL匹配@GetMapping(value = "/consumer-feign/{str}")。如果針對圖中的url做限流規則,只會影響到一種url請求。比如對/consumer-feign/123做限流規則不會影響/consumer-feign/456請求。如果想控制所有符合/consumer-feign/{str}規則的請求  推薦對這種Mapping增加@SentinelResource統一資源掛載點。然後針對@SentinelResource做限流

   
    /**
     * @SentinelResource 資源埋點
     * 通過AOP包裝被標註方法,監控其執行時間等信息
     * 註解說明 https://github.com/alibaba/Sentinel/wiki/%E6%B3%A8%E8%A7%A3%E6%94%AF%E6%8C%81
     * @param str
     * @return
     */
    @GetMapping(value = "/consumer-feign/{str}")
    @SentinelResource(value = "demo-consumer/consumer-feign",blockHandler = "blockHandler",fallback = "fallHandler")
    public String feign(@PathVariable String str) {
        //fegin
        return echoService.echo(str);
    }
    /**
     * 原方法調用被配置的流控規則限流時觸發BlockException,調用blockHandler
     * @param str 原方法參數
     * @param ex 異常
     * @return
     */
    public String blockHandler(String str, BlockException ex) {
        return "Sentinel-blockback "+str;
    }
    /**
     * 原方法調用觸發配置的降級規則時拋出DegradeException,調用fallback
     * fallback還可以捕獲業務異常
     * @param str
     * @return
     */
    public String fallHandler(String str) {
        return "Sentinel-fallback "+str;
    }

5 降級處理

@FeignClient和@SentinelResource都可以配置降級,但是在Sentinel環境下推薦使用@SentinelResource配置。測試時@FeignClient的fallback配置偶爾會失效。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章