Spring Cloud集成Sentinel
Spring Cloud Alibaba 默認(rèn)為Sentinel整合了Servlet、RestTemplate、FeignClient和SpringWebFlux。Sentinel補(bǔ)全了Hystrix在Servlet和RestTemplate的不足,還兼容了Hystrix在FeignClient中限流降級的用法,支持靈活配置和調(diào)整流控規(guī)則。
Sentinel接入Spring Cloud
創(chuàng)建一個(gè)基于SpringBoot的項(xiàng)目,并集成SpringCloud依賴
-
添加Sentinel依賴
<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> <version>2.2.5.RELEASE</version> </dependency> 復(fù)制代碼 創(chuàng)建一個(gè)REST接口,并使用@SentinelResource配置限流保護(hù)資源
@RestController
@RequestMapping("/sentinel")
public class SentinelController {
@SentinelResource(value = "getName",blockHandler = "blockHandlerMethodByLimit")
@GetMapping(value = "/{name}")
public String getName(@PathVariable("name") String name){
return name;
}
public String blockHandlerMethodByLimit(BlockException e){
return "被限流";
}
}
復(fù)制代碼
配置限流資源有以下幾種情況
- Sentinel Starter在默認(rèn)下為所有的HTTP服務(wù)提供限流埋點(diǎn),只想對HTTP服務(wù)限流,只需要添加依賴,無需修改代碼
- 針對特定的方法限流或者降級,使用@SentinelResource注解來實(shí)現(xiàn)限流資源的定義
- 通過SphU.entry()配置資源
手動配置流量控制規(guī)則,是借助了Sentinel的InitFunc SPI擴(kuò)展接口實(shí)現(xiàn),需要實(shí)現(xiàn)InitFunc接口,并在init方法編寫相關(guān)規(guī)則邏輯
public class FlowRlueInitFunc implements InitFunc {
@Override
public void init() throws Exception {
List<FlowRule> list = new ArrayList<>();
FlowRule flowRule = new FlowRule();
flowRule.setCount(1);
flowRule.setResource("getName");
flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
flowRule.setLimitApp("default");
list.add(flowRule);
FlowRuleManager.loadRules(list);
}
}
復(fù)制代碼
SPI是擴(kuò)展點(diǎn)機(jī)制,需要被Sentinel加載,還要在resource目錄下創(chuàng)建META-INF/services/com.alibaba.csp.sentinel.init.InitFunc文件,文件內(nèi)容是自定義擴(kuò)展點(diǎn)的全路徑
com.ozx.springcloud.sentinel.util.FlowRuleInitFunc
按照以上配置好后,在初次訪問任何資源時(shí),Sentinel就會自動加載getName資源的流控規(guī)則。
啟動服務(wù)后,訪問http://localhost:8080/sentinel/Gxin方法,當(dāng)訪問頻率超過閾值時(shí),會觸發(fā)限流。

以上配置過程是基于手動配置來加載Sentinel流量控制規(guī)則,之后下一篇文章介紹另一種方式是通過Sentinel Dashboard來配置相關(guān)流控規(guī)則。
作者:Gxin
鏈接:https://juejin.cn/post/6994711316111818766
來源:掘金