Sentinel 是阿里開源的分布式流量哨兵,具有限流、熔斷降級、服務監控等功能,
下面介紹在 SpringCloud中的具體使用方式,
目錄
1. 下載并啟動 Sentinel 控制臺服務
2. 引入起步依賴
3. 配置
4. 代碼
5. 使用
6. 驗證結果
1. 下載并啟動 Sentinel 控制臺服務
java -Dserver.port=8070 -Dcsp.sentinel.dashboard.server=localhost:8070 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard-1.8.2.jar
2. 引入起步依賴
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>
3. 配置
spring:
profiles:
active: dev
application:
name: springboot-hello
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8849
config:
server-addr: 127.0.0.1:8849
# 擴展名必須要嚴格一致:springboot-hello-dev.yml,
# 如果配置成 .yaml, 則 springboot-hello-dev.yaml
file-extension: yml
sentinel:
transport:
dashboard: localhost:8070
server:
port: 9000
4. 代碼
/**
* 被呼叫方的 sentinel fallback 優先呼叫方的 feignClient 的 fallback
*
* 1. fallback 是例外降級,只要出現業務例外后,會走 fallback 指定的方法;
* 2. 達到相應的閾值時,才會觸發熔斷和限流,都會拋出 BlockException 由 blockHandler 方法處理;
*
*/
@SentinelResource(value = "sayHello", fallback = "sayDefaultHello",blockHandler = "blockWarn")
@RequestMapping("/hello")
@RequestMapping("/hello")
public String hello(){
int b = 1/0;
return String.format("Hello 【%s】", username);
}
// 例外降級,只針對業務例外!
public String sayDefaultHello(){
return String.format("Hello World!");
}
// 熔斷降級、流控 都會觸發 BlockException
public String blockWarn(BlockException e) {
if (e instanceof FlowException) {
return "訪問太頻繁,稍后重試!";
}
if (e instanceof DegradeException) {
return "服務已自動斷開,稍后重試!";
}
return "稍后重試";
}
5. 使用
在 dashboard 配置流控規則和熔斷規則:

6. 驗證結果
1. 首次訪問,觸發 fallback

2. 連續頻繁重繪,觸發限流

3. 訪問多次,達到熔斷策略,觸發熔斷

如果覺得還不錯的話,關注、分享、在看(關注不失聯~), 原創不易,且看且珍惜~

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/310534.html
標籤:其他
上一篇:網路協議:網路基礎
下一篇:Spring Cloud+Spring Boot+Mybatis+ElementUI 實作前后端分離之企業快速開發平臺業務服務
