在 Sentinel 中资源定义和规则配置是分离的。先通过 Sentinel API 给对应的业务逻辑定义资源(埋点),然后可以在需要的时候配置规则。
1,引入依赖包
com.alibaba.csp
sentinel-core
1.8.0
com.alibaba.csp
sentinel-annotation-aspectj
1.8.0
使用方式一:Java原生编码方式
步骤1:定义需要保护的资源
public String test(){
Entry entry = null;
try {
//定义资源保护的入口,同时指定资源名(用于与规则匹配)
entry = SphU.entry("sentinelApi");
//业务逻辑(这了调用了另一个方法)
return getMsg() ;
} catch (BlockException e) {
if(e instanceof FlowException){
//限流控制逻辑处理
return "限流了" ;
}
if(e instanceof DegradeException){
//熔断控制逻辑处理
return "降级了" ;
}
return "none" ;
} catch (Exception e){
//记录业务异常数
Tracer.trace(e) ;
return "exe" ;
}finally {
if (entry != null) {
entry.exit();
}
}
}
步骤2:定义资源保护规则
@Component
public class SentinelRuleConfiguration {
@PostConstruct
public void init() {
//限流规则
initFlowRule("sentinelApi") ;
//熔断降级规则
initDegradeRule("sentinelApi") ;
//添加时间监听
addEventObserver() ;
}
/**
*
* 流量控制(flow control),其原理是监控应用流量的 QPS 或并发线程数等指标,
* 当达到指定的阈值时对流量进行控制,以避免被瞬时的流量高峰冲垮,从而保障应用的高可用性。
*
* 限流的直接表现是在执行 Entry nodeA = SphU.entry(resourceName) 的时候抛出 FlowException 异常。
* FlowException 是 BlockException 的子类,您可以捕捉 BlockException 来自定义被限流之后的处理逻辑。
*
* 流量控制规则 (FlowRule).
* 同一个资源可以同时有多个限流规则,检查规则时会依次检查。
* @param resourceName 资源名,资源名是限流规则的作用对象
* */
private static void initFlowRule(String resourceName) {
List rules = new ArrayList<>();
/*
* 配置策略1: 并发线程数控制【通常在调用端进行配置】
* 并发数控制用于保护业务线程池不被慢调用耗尽
* */
FlowRule thRule = new FlowRule(resourceName);
thRule.setCount(1); //限流阈值
thRule.setGrade(RuleConstant.FLOW_GRADE_THREAD); //限流阈值类型,QPS 模式(1)或并发线程数模式(0)。默认:QPS