Sentinel 限流降級,Sentinel持久化
================================
©Copyright 蕃薯耀 2021-04-01
https://www.cnblogs.com/fanshuyao/
一、Sentinel安裝使用和配置,sentinel-dashboard安裝使用和配置
見:
https://www.cnblogs.com/fanshuyao/p/14606396.html
二、Sentinel 限流降級配置
1、pom.xml引入依賴
<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> </dependency>
2、application.properties配置文件增加sentinel配置:
spring.cloud.sentinel.transport.port=8719 spring.cloud.sentinel.transport.dashboard=localhost:8070 spring.cloud.sentinel.log.dir=C:/logs/sentinel-web
3、Sentinel簡單限流(url匹配限流)
import org.springframework.beans.factory.annotation.Value; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.lqy.springCloud.Result; @RestController @RequestMapping("/") public class SentinelController { @Value("${server.port}") private String serverPort; @RequestMapping(value="/sentinel", produces = MediaType.APPLICATION_JSON_VALUE) public Result sentinel() { return Result.ok(serverPort); } }
瀏覽器打開:
http://localhost:8070/
在Sentinel dashboard配置/sentinel的限流規則,每秒只能訪問一次,超出訪問,就會限流,返回默認的提示:
Blocked by Sentinel (flow limiting)
打開瀏覽器頻繁訪問(1秒內必須超過一次請求):
http://127.0.0.1:8901/sentinel
4、@SentinelResource注解使用
import org.springframework.beans.factory.annotation.Value; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.alibaba.csp.sentinel.annotation.SentinelResource; import com.alibaba.csp.sentinel.slots.block.BlockException; import com.lqy.springCloud.Result; @RestController @RequestMapping("/") public class SentinelController { @Value("${server.port}") private String serverPort; //blockHandler 函數會在原方法被限流/降級/系統保護的時候調用,而 fallback 函數會針對所有類型的異常。 @RequestMapping(value="/limit", produces = MediaType.APPLICATION_JSON_VALUE) @SentinelResource(value="limit", blockHandler = "limitBlockHandler") public Result limit() { return Result.ok(serverPort); } public Result limitBlockHandler(BlockException be) { return Result.fail(serverPort); } }
@SentinelResource中,value配置的是資源名,不帶有/,blockHandler配置的是限流回調的方法
@SentinelResource不生效:
出現一個@SentinelResource不生效的情況,
原因是:在Sentinel dashboard同時配置了/limit和limit兩個限流規划,導致limit不生效,blockHandler不被回調。
blockHandler 函數訪問范圍需要是 public,返回類型需要與原方法相匹配,參數類型需要和原方法相匹配並且最后加一個額外的參數,類型為 BlockException。
blockHandler 函數默認需要和原方法在同一個類中。若希望使用其他類的函數,則可以指定 blockHandlerClass 為對應的類的 Class 對象,注意對應的函數必需為 static 函數,否則無法解析。
5、Sentinel fallback異常處理
import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.alibaba.csp.sentinel.annotation.SentinelResource; import com.alibaba.csp.sentinel.slots.block.BlockException; import com.lqy.springCloud.Result; @RestController @RequestMapping("/") public class SentinelController { //blockHandler 函數會在原方法被限流/降級/系統保護的時候調用,而 fallback 函數會針對所有類型的異常。 @RequestMapping(value="/fallback", produces = MediaType.APPLICATION_JSON_VALUE) @SentinelResource(value="fallback", blockHandler = "limitBlockHandler", fallback = "failFallback") public Result fail(String a) { if(StringUtils.isBlank(a)) { throw new RuntimeException("參數錯誤"); } return Result.ok(null, a); } //參數要一致,不然fallback匹配不到,后面可以多一個Throwable參數 public Result failFallback(String a, Throwable t) { return Result.failMsg("出現異常:" + serverPort); } }
正常結果:
// http://127.0.0.1:8901/fallback?a=11 { "result": true, "timestamp": "2021-03-30 15:22:10", "msg": "操作成功。", "datas": "11" }
Fallback結果:
// http://127.0.0.1:8901/fallback { "result": false, "timestamp": "2021-03-30 15:21:25", "msg": "出現異常:8901", "datas": null }
fallback 函數名稱,可選項,用於在拋出異常的時候提供 fallback 處理邏輯。fallback 函數可以針對所有類型的異常(除了 exceptionsToIgnore 里面排除掉的異常類型)進行處理。
fallback 函數簽名和位置要求:
返回值類型必須與原函數返回值類型一致;
方法參數列表需要和原函數一致,或者可以額外多一個 Throwable 類型的參數用於接收對應的異常。
fallback 函數默認需要和原方法在同一個類中。若希望使用其他類的函數,則可以指定 fallbackClass 為對應的類的 Class 對象,注意對應的函數必需為 static 函數,否則無法解析。
注:1.6.0 之前的版本 fallback 函數只針對降級異常(DegradeException)進行處理,不能針對業務異常進行處理。
若 blockHandler 和 fallback 都進行了配置,則被限流降級而拋出 BlockException 時只會進入 blockHandler 處理邏輯。
6、同時配置blockHandler和fallback
若 blockHandler 和 fallback 都進行了配置,則被限流降級而拋出 BlockException 時只會進入 blockHandler 處理邏輯。
當配置了blockHandler,但blockHandler沒有匹配上的時候(如參數不一致),會使用fallback異常處理返回
import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.alibaba.csp.sentinel.annotation.SentinelResource; import com.alibaba.csp.sentinel.slots.block.BlockException; import com.lqy.springCloud.Result; @RestController @RequestMapping("/") public class SentinelController { //blockHandler 函數會在原方法被限流/降級/系統保護的時候調用,而 fallback 函數會針對所有類型的異常。 @RequestMapping(value="/fallback", produces = MediaType.APPLICATION_JSON_VALUE) @SentinelResource(value="fallback", blockHandler = "failBlockHandler", fallback = "failFallback") public Result fail(String a) { if(StringUtils.isBlank(a)) { throw new RuntimeException("參數錯誤"); } return Result.ok(null, a); } public Result failBlockHandler(String a, BlockException be) { return Result.fail("failBlockHandler:" + serverPort); } //參數要一致,不然fallback匹配不到,后面可以多一個Throwable參數 //當配置了blockHandler,但blockHandler沒有匹配上的時候,會使用fallback異常處理返回 public Result failFallback(String a, Throwable t) { return Result.failMsg("出現異常:" + serverPort); } }
// http://127.0.0.1:8901/fallback?a=11 { "result": false, "timestamp": "2021-03-30 15:27:05", "msg": "操作失敗!", "datas": "failBlockHandler:8901" }
7、Sentinel自定義blockHandlerClass和自定義fallbackClass
import com.alibaba.csp.sentinel.slots.block.BlockException; import com.lqy.springCloud.Result; /** * 自定義BlockHandler * 方法必需為 static 方法,否則無法解析 * */ public class MyBlockHandler { /** * 參數一定要和方法對應,否則無法匹配到 * @param a * @param be BlockException * @return */ public static Result blockHandler(String a, BlockException be) { return Result.fail("訪問頻繁,請稍候再試"); } /** * 參數一定要和方法對應,否則無法匹配到 * @param a * @param t Throwable * @return */ public static Result exceptionHandler(String a, Throwable t) { return Result.fail("服務暫時不可用,請稍候再試"); } }
自定義blockHandlerClass和fallbackClass
import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.alibaba.csp.sentinel.annotation.SentinelResource; import com.alibaba.csp.sentinel.slots.block.BlockException; import com.lqy.springCloud.Result; @RestController @RequestMapping("/") public class SentinelController { @Value("${server.port}") private String serverPort; //自定義blockHandlerClass和fallbackClass //注意對應的函數必需為 static 函數,否則無法解析。 @RequestMapping(value="/myBlockHandler", produces = MediaType.APPLICATION_JSON_VALUE) @SentinelResource(value="myBlockHandler", blockHandlerClass = MyBlockHandler.class, blockHandler = "blockHandler", fallbackClass = MyBlockHandler.class, fallback = "exceptionHandler") public Result myBlockHandler(String a) { if(StringUtils.isBlank(a)) { throw new RuntimeException("參數錯誤"); } return Result.ok(null, a); } }
測試結果:
// http://127.0.0.1:8901/myBlockHandler?a=11 { "result": false, "timestamp": "2021-03-30 15:56:03", "msg": "操作失敗!", "datas": "訪問頻繁,請稍候再試" } // http://127.0.0.1:8901/myBlockHandler { "result": false, "timestamp": "2021-03-30 15:57:28", "msg": "操作失敗!", "datas": "服務暫時不可用,請稍候再試" }
8、Sentinel exceptionsToIgnore:
(since 1.6.0),用於指定哪些異常被排除掉,不會計入異常統計中,也不會進入 fallback 邏輯中,而是會原樣拋出。
9、Sentinel全局限流降級結果返回
實現BlockExceptionHandler接口,實現handle方法。
舊版本的sentinel是實現UrlBlockHandler接口,新版本(1.8版本)是沒有這個接口的。
默認的結果處理類是:
com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.DefaultBlockExceptionHandler
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler; import com.alibaba.csp.sentinel.slots.block.BlockException; import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException; import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException; import com.alibaba.csp.sentinel.slots.block.flow.FlowException; import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException; import com.alibaba.csp.sentinel.slots.system.SystemBlockException; import com.lqy.springCloud.Result; import cn.hutool.json.JSONUtil; @Component public class SentinelExceptionHandler implements BlockExceptionHandler { @Override public void handle(HttpServletRequest request, HttpServletResponse response, BlockException ex) throws Exception { String msg = null; if (ex instanceof FlowException) { msg = "訪問頻繁,請稍候再試"; } else if (ex instanceof DegradeException) { msg = "系統降級"; } else if (ex instanceof ParamFlowException) { msg = "熱點參數限流"; } else if (ex instanceof SystemBlockException) { msg = "系統規則限流或降級"; } else if (ex instanceof AuthorityException) { msg = "授權規則不通過"; } else { msg = "未知限流降級"; } // http狀態碼 response.setStatus(500); response.setCharacterEncoding("utf-8"); response.setHeader("Content-Type", "application/json;charset=utf-8"); response.setContentType("application/json;charset=utf-8"); response.getWriter().write(JSONUtil.toJsonStr(Result.failMsg(msg))); } }
三、Sentinel持久化配置
1、pom.xml引入依賴
<dependency> <groupId>com.alibaba.csp</groupId> <artifactId>sentinel-datasource-nacos</artifactId> </dependency>
2、sentinel結合Nacos持久化配置
sentinel持久化支持的類型有,詳情見:
com.alibaba.cloud.sentinel.datasource.config.DataSourcePropertiesConfiguration
private FileDataSourceProperties file;
private NacosDataSourceProperties nacos;
private ZookeeperDataSourceProperties zk;
private ApolloDataSourceProperties apollo;
private RedisDataSourceProperties redis;
private ConsulDataSourceProperties consul;
sentinel結合Nacos持久化配置:
#sentinel結合Nacos持久化配置 #配置的屬性見:com.alibaba.cloud.sentinel.datasource.config.NacosDataSourceProperties spring.cloud.sentinel.datasource.ds1.nacos.server-addr=http://127.0.0.1:8848 spring.cloud.sentinel.datasource.ds1.nacos.data-id=sentinel-config #//group-id默認是:DEFAULT_GROUP spring.cloud.sentinel.datasource.ds1.nacos.group-id=SENTINEL_GROUP #RuleType類型見:com.alibaba.cloud.sentinel.datasource.RuleType #data-type這個屬性沒有提示,和Nacos配置的類型保持一致,配置在:com.alibaba.cloud.sentinel.datasource.config.AbstractDataSourceProperties spring.cloud.sentinel.datasource.ds1.nacos.data-type=json #authority(授權規則)、degrade(降級規則)、flow(流控規則)、param(熱點規則)、system(系統規則)五種規則持久化到Nacos中。 另外還增加網關的兩個(api分組,限流) #rule-type這個屬性沒有提示,為空時,會報空指針錯誤 spring.cloud.sentinel.datasource.ds1.nacos.rule-type=flow
每種數據源都有兩個共同的配置項: data-type、 converter-class 以及 rule-type,配置在:
com.alibaba.cloud.sentinel.datasource.config.AbstractDataSourceProperties
data-type 配置項表示 Converter 類型,Spring Cloud Alibaba Sentinel 默認提供兩種內置的值,分別是 json 和 xml (不填默認是json)。
如果不想使用內置的 json 或 xml 這兩種 Converter,可以填寫 custom 表示自定義 Converter,然后再配置 converter-class 配置項,該配置項需要寫類的全路徑名(比如 spring.cloud.sentinel.datasource.ds1.file.converter-class=com.alibaba.cloud.examples.JsonFlowRuleListConverter)。
rule-type 配置表示該數據源中的規則屬於哪種類型的規則(flow,degrade,authority,system, param-flow, gw-flow, gw-api-group)。
注意:
當某個數據源規則信息加載失敗的情況下,不會影響應用的啟動,會在日志中打印出錯誤信息。
默認情況下,xml 格式是不支持的。需要添加 jackson-dataformat-xml 依賴后才會自動生效。
如果規則加載沒有生效,有可能是 jdk 版本導致的,請關注 759 issue 的處理。
sentinel缺少spring.cloud.sentinel.datasource.ds1.nacos.rule-type報錯:DataSource ds1 build error: null
2021-03-31 11:20:59.718 ERROR 12168 --- [ restartedMain] c.a.c.s.c.SentinelDataSourceHandler : [Sentinel Starter] DataSource ds1 build error: null java.lang.NullPointerException: null at com.alibaba.cloud.sentinel.custom.SentinelDataSourceHandler.lambda$registerBean$3(SentinelDataSourceHandler.java:185) ~[spring-cloud-starter-alibaba-sentinel-2.2.5.RELEASE.jar:2.2.5.RELEASE] at java.util.HashMap.forEach(HashMap.java:1289) ~[na:1.8.0_241] at com.alibaba.cloud.sentinel.custom.SentinelDataSourceHandler.registerBean(SentinelDataSourceHandler.java:128) ~[spring-cloud-starter-alibaba-sentinel-2.2.5.RELEASE.jar:2.2.5.RELEASE] at com.alibaba.cloud.sentinel.custom.SentinelDataSourceHandler.lambda$afterSingletonsInstantiated$0(SentinelDataSourceHandler.java:93) ~[spring-cloud-starter-alibaba-sentinel-2.2.5.RELEASE.jar:2.2.5.RELEASE] at java.util.TreeMap.forEach(TreeMap.java:1005) ~[na:1.8.0_241] at com.alibaba.cloud.sentinel.custom.SentinelDataSourceHandler.afterSingletonsInstantiated(SentinelDataSourceHandler.java:80) ~[spring-cloud-starter-alibaba-sentinel-2.2.5.RELEASE.jar:2.2.5.RELEASE]
原因就是com.alibaba.cloud.sentinel.custom.SentinelDataSourceHandler.registerBean(AbstractDataSourceProperties, String)中的dataSourceProperties.getRuleType()為空,所以配置文件中的spring.cloud.sentinel.datasource.ds1.nacos.rule-type不能為空。
// converter type now support xml or json. // The bean name of these converters wrapped by // 'sentinel-{converterType}-{ruleType}-converter' builder.addPropertyReference("converter", "sentinel-" + propertyValue.toString() + "-" + dataSourceProperties.getRuleType().getName() + "-converter");
提示是沒有rule-type屬性的,可能是因為rule-type是繼承過來的或者是開發工具的問題。
rule-type在Sts提示沒有該屬性,但啟動是沒問題的。
3、Nacos增加配置文件
data-id名稱為:sentinel-config
group名稱為:SENTINEL_GROUP
配置格式:選擇JSON
配置內容如下:
[ { "resource": "myBlockHandler", "limitApp": "default", "grade": "1", "count": "1", "strategy": "0", "controlBehavior": "0", "clusterMode": false } ]
【流控規則】配置項說明:
resource:資源名
limitApp:針對來源,若為 default 則不區分調用來源
grade:閾值類型,0表示線程數,1表示QPS
count:單機閾值
strategy:流控模式,0表示直接,1表示關聯,2表示鏈路
controlBehavior:流控效果,0表示快速失敗,1表示Warm Up,2表示排隊等待
clusterMode:是否集群
配置多個規則:
[ { "resource": "myBlockHandler", "limitApp": "default", "grade": "1", "count": "1", "strategy": "0", "controlBehavior": "0", "clusterMode": false }, { "resource": "flowLimit", "limitApp": "default", "grade": "1", "count": "1", "strategy": "0", "controlBehavior": "0", "clusterMode": false } ]
Nacos配置文件發布后,會馬上在Sentinel更新。
4、測試Sentinel持久化
sentinel是懶加載機制,只有當服務發起了請求,控制台才能看到並進行操作。
瀏覽器打開鏈接:
http://127.0.0.1:8901/myBlockHandler?a=11
請求后,查看Sentinel是否已經加載配置。
四、其它限流規則
1、Sentinel熔斷降級規則說明
熔斷降級規則(DegradeRule)包含下面幾個重要的屬性:
Field 說明 默認值 resource 資源名,即規則的作用對象 grade 熔斷策略,支持慢調用比例/異常比例/異常數策略 慢調用比例 count 慢調用比例模式下為慢調用臨界 RT(超出該值計為慢調用);異常比例/異常數模式下為對應的閾值 timeWindow 熔斷時長,單位為 s minRequestAmount 熔斷觸發的最小請求數,請求數小於該值時即使異常比率超出閾值也不會熔斷(1.7.0 引入) 5 statIntervalMs 統計時長(單位為 ms),如 60*1000 代表分鍾級(1.8.0 引入) 1000 ms slowRatioThreshold 慢調用比例閾值,僅慢調用比例模式有效(1.8.0 引入)
2、Sentinel【熱點規則】熱點參數規則
熱點參數規則(ParamFlowRule)類似於流量控制規則(FlowRule):
屬性 說明 默認值 resource 資源名,必填 count 限流閾值,必填 grade 限流模式 QPS 模式 durationInSec 統計窗口時間長度(單位為秒),1.6.0 版本開始支持 1s controlBehavior 流控效果(支持快速失敗和勻速排隊模式),1.6.0 版本開始支持 快速失敗 maxQueueingTimeMs 最大排隊等待時長(僅在勻速排隊模式生效),1.6.0 版本開始支持 0ms paramIdx 熱點參數的索引,必填,對應 SphU.entry(xxx, args) 中的參數索引位置 paramFlowItemList 參數例外項,可以針對指定的參數值單獨設置限流閾值,不受前面 count 閾值的限制。僅支持基本類型和字符串類型 clusterMode 是否是集群參數流控規則 false clusterConfig 集群流控相關配置
3、Sentinel系統規則
系統保護規則是從應用級別的入口流量進行控制,從單台機器的 load、CPU 使用率、平均 RT、入口 QPS 和並發線程數等幾個維度監控應用指標,讓系統盡可能跑在最大吞吐量的同時保證系統整體的穩定性。
系統保護規則是應用整體維度的,而不是資源維度的,並且僅對入口流量生效。入口流量指的是進入應用的流量(EntryType.IN),比如 Web 服務或 Dubbo 服務端接收的請求,都屬於入口流量。
系統規則支持以下的模式:
Load 自適應(僅對 Linux/Unix-like 機器生效):系統的 load1 作為啟發指標,進行自適應系統保護。當系統 load1 超過設定的啟發值,且系統當前的並發線程數超過估算的系統容量時才會觸發系統保護(BBR 階段)。系統容量由系統的 maxQps * minRt 估算得出。設定參考值一般是 CPU cores * 2.5。
CPU usage(1.5.0+ 版本):當系統 CPU 使用率超過閾值即觸發系統保護(取值范圍 0.0-1.0),比較靈敏。
平均 RT:當單台機器上所有入口流量的平均 RT 達到閾值即觸發系統保護,單位是毫秒。
並發線程數:當單台機器上所有入口流量的並發線程數達到閾值即觸發系統保護。
入口 QPS:當單台機器上所有入口流量的 QPS 達到閾值即觸發系統保護。
系統規則json文件配置(最簡單配置),配置QPS為1:
[ { "qps":1.0 } ]
系統規則json文件配置,配置QPS為1(這段json配置是從新增那里獲取的,能正常持久化):
[ { "id":12, "app":"SPRING-CLOUD-SENTINEL", "ip":"192.168.170.1", "port":8720, "highestSystemLoad":-1.0, "avgRt":-1, "maxThread":-1, "qps":1.0, "highestCpuUsage":-1.0, "gmtCreate":null, "gmtModified":null } ]
highestSystemLoad:對應頁面的Load
avgRt:對應頁面的RT
maxThread:對應頁面的線程數
qps:對應入口QPS
highestCpuUsage:對應CUP使用率
五、、Feign 支持
Sentinel 適配了 Feign 組件。如果想使用,除了引入 spring-cloud-starter-alibaba-sentinel 的依賴外還需要 2 個步驟:
配置文件打開 Sentinel 對 Feign 的支持:feign.sentinel.enabled=true
加入 spring-cloud-starter-openfeign 依賴使 Sentinel starter 中的自動化配置類生效:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
六、RestTemplate 支持
Spring Cloud Alibaba Sentinel 支持對 RestTemplate 的服務調用使用 Sentinel 進行保護,在構造 RestTemplate bean的時候需要加上 @SentinelRestTemplate 注解。
@Bean @SentinelRestTemplate(blockHandler = "handleException", blockHandlerClass = ExceptionUtil.class) public RestTemplate restTemplate() { return new RestTemplate(); }
@SentinelRestTemplate 注解的屬性支持限流(blockHandler, blockHandlerClass)和降級(fallback, fallbackClass)的處理。
其中 blockHandler 或 fallback 屬性對應的方法必須是對應 blockHandlerClass 或 fallbackClass 屬性中的靜態方法。
注意:應用啟動的時候會檢查 @SentinelRestTemplate 注解對應的限流或降級方法是否存在,如不存在會拋出異常
@SentinelRestTemplate 注解的限流(blockHandler, blockHandlerClass)和降級(fallback, fallbackClass)屬性不強制填寫。
當使用 RestTemplate 調用被 Sentinel 熔斷后,會返回 RestTemplate request block by sentinel 信息,或者也可以編寫對應的方法自行處理返回信息。這里提供了 SentinelClientHttpResponse 用於構造返回信息。
Sentinel RestTemplate 限流的資源規則提供兩種粒度:
httpmethod:schema://host:port/path:協議、主機、端口和路徑
httpmethod:schema://host:port:協議、主機和端口
七、動態數據源支持
SentinelProperties 內部提供了 TreeMap 類型的 datasource 屬性用於配置數據源信息。
比如配置 4 個數據源:
spring.cloud.sentinel.datasource.ds1.file.file=classpath: degraderule.json spring.cloud.sentinel.datasource.ds1.file.rule-type=flow #spring.cloud.sentinel.datasource.ds1.file.file=classpath: flowrule.json #spring.cloud.sentinel.datasource.ds1.file.data-type=custom #spring.cloud.sentinel.datasource.ds1.file.converter-class=com.alibaba.cloud.examples.JsonFlowRuleListConverter #spring.cloud.sentinel.datasource.ds1.file.rule-type=flow spring.cloud.sentinel.datasource.ds2.nacos.server-addr=localhost:8848 spring.cloud.sentinel.datasource.ds2.nacos.data-id=sentinel spring.cloud.sentinel.datasource.ds2.nacos.group-id=DEFAULT_GROUP spring.cloud.sentinel.datasource.ds2.nacos.data-type=json spring.cloud.sentinel.datasource.ds2.nacos.rule-type=degrade spring.cloud.sentinel.datasource.ds3.zk.path = /Sentinel-Demo/SYSTEM-CODE-DEMO-FLOW spring.cloud.sentinel.datasource.ds3.zk.server-addr = localhost:2181 spring.cloud.sentinel.datasource.ds3.zk.rule-type=authority spring.cloud.sentinel.datasource.ds4.apollo.namespace-name = application spring.cloud.sentinel.datasource.ds4.apollo.flow-rules-key = sentinel spring.cloud.sentinel.datasource.ds4.apollo.default-flow-rule-value = test spring.cloud.sentinel.datasource.ds4.apollo.rule-type=param-flow
d1, ds2, ds3, ds4 是 ReadableDataSource 的名字,可隨意編寫。后面的 file ,zk ,nacos , apollo 就是對應具體的數據源,它們后面的配置就是這些具體數據源各自的配置。注意數據源的依賴要單獨引入(比如 sentinel-datasource-nacos)。
每種數據源都有兩個共同的配置項: data-type、 converter-class 以及 rule-type。
data-type 配置項表示 Converter 類型,Spring Cloud Alibaba Sentinel 默認提供兩種內置的值,分別是 json 和 xml (不填默認是json)。
如果不想使用內置的 json 或 xml 這兩種 Converter,可以填寫 custom 表示自定義 Converter,然后再配置 converter-class 配置項,該配置項需要寫類的全路徑名(比如 spring.cloud.sentinel.datasource.ds1.file.converter-class=com.alibaba.cloud.examples.JsonFlowRuleListConverter)。
rule-type 配置表示該數據源中的規則屬於哪種類型的規則(flow,degrade,authority,system, param-flow, gw-flow, gw-api-group)。
八、Spring Cloud Gateway 支持
若想跟 Sentinel Starter 配合使用,需要加上 spring-cloud-alibaba-sentinel-gateway 依賴,同時需要添加 spring-cloud-starter-gateway 依賴來讓 spring-cloud-alibaba-sentinel-gateway 模塊里的 Spring Cloud Gateway 自動化配置類生效:
<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency>
同時請將 spring.cloud.sentinel.filter.enabled 配置項置為 false(若在網關流控控制台上看到了 URL 資源,就是此配置項沒有置為 false)。
九、Endpoint 支持
在使用 Endpoint 特性之前需要在 Maven 中添加 spring-boot-starter-actuator 依賴,並在配置中允許 Endpoints 的訪問。
Spring Boot 1.x 中添加配置 management.security.enabled=false。暴露的 endpoint 路徑為 /sentinel
Spring Boot 2.x 中添加配置 management.endpoints.web.exposure.include=*。暴露的 endpoint 路徑為 /actuator/sentinel
Sentinel Endpoint 里暴露的信息非常有用。包括當前應用的所有規則信息、日志目錄、當前實例的 IP,Sentinel Dashboard 地址,Block Page,應用與 Sentinel Dashboard 的心跳頻率等等信息。
十、Sentinel 、Hystrix、Resilience4j 功能對比
(時間寶貴,分享不易,捐贈回饋,^_^)
================================
©Copyright 蕃薯耀 2021-04-01
https://www.cnblogs.com/fanshuyao/