一、簡介
默認情況下,我們在控制檯配置的規則並不會持久化,當項目重新啓動之後,配置就會刪除,這裏我們整合 apollo + sentinel 進行配置持久化。
二、實例
1、添加核心依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-alibaba-sentinel -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-apollo</artifactId>
<version>1.4.1</version>
</dependency>
2、示例代碼
@RestController
public class IndexController {
@RequestMapping("/index")
public String index() {
return "index";
}
@SentinelResource(value = "getIndexConsole",blockHandler = "getOrderQpsEx")
@RequestMapping("/getIndexConsole")
public String getIndexConsole() {
return "getIndexConsole";
}
public String getOrderQpsEx(BlockException e) {
return "接口已經被限流";
}
}
3、yml 配置文件
spring:
application:
name: sentinel
cloud:
sentinel:
transport:
dashboard: localhost:8718
eager: true
datasource:
ds:
apollo:
namespace-name: application
flow-rules-key: sentinel.flowRules
rule-type: flow
server:
port: 8889
tomcat:
max-threads: 20
app:
id: sentinel
apollo:
meta: http://**.**.*.171:8080/
cacheDir: /app/war/apollo/temp/
4、在 Apollo 配置中心添加配置
Apollo 配置中心創建項目 sentinel並添加以下配置
key
flowRules
val
[
{
"resource": "getIndexConsole",
"limitApp": "default",
"grade": 1,
"count": 1,
"strategy": 0,
"controlBehavior": 0,
"clusterMode": false
}
]
resource
資源名,限流的接口
limitApp
流控針對的調用來源,default 不區分來源
grade
限流閾值類型,0代表根據線程數,1代表根據 Qps
count
限流閾值
strategy
採用策略
controlBehavior
流控效果, (快速失敗 Warm Up 排隊等待)
clusterMode
是否集羣
三、結果測試
1、啓動控制檯
2、啓動項目
如果 Apollo 部署在 Docker 或者公網,添加啓動參數
-Dapollo.configService=http://**.**.*.171:8080
3、在 Apollo 發佈配置
Apollo 的配置已經刷新到控制檯
4、訪問接口
http://localhost:8889/getIndexConsole
四、代碼示例
https://github.com/huangliangyun/alibaba-learning/tree/master/spring-cloud-alibaba
—— 完
看完覺得有用,記得點贊,關注,轉發!
ABOUT
我的 Github:Github
CSDN: CSDN
個人網站: sirius blog
參考資料
https://github.com/alibaba/Sentinel/wiki/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%99%E6%89%A9%E5%B1%95
https://github.com/alibaba/spring-cloud-alibaba/wiki/Sentinel
http://blog.didispace.com/spring-cloud-alibaba-sentinel-2-2/