首先基础操作,看完直接就能用,然后希望阿里改进的地方,并提issue,自己实现思路:
只简单介绍限流和异常降级,其他大同小异:
1.限流:
(1)非注解方式:
规则:
@PostConstruct
public void rule() {
FlowRule rule1 = new FlowRule();
rule1.setResource("call");
rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);
//每秒只允许5个请求
rule1.setCount(5);
List<FlowRule> rules = new ArrayList<>();
rules.add(rule1);
FlowRuleManager.loadRules(rules);
}
业务代码:
@GetMapping("test")
public Object test() {
Entry entry = null;
try {
//这里定义资源名,对应规则
entry = SphU.entry("call");
return "ok";
} catch (BlockException e) {
//触发限流进入这里
return "限流了";
} finally {
//这里一定要释放
if (entry != null) {
entry.exit();
}
}
}
(2)注解模式
定义熔断业务:
//写在当前类中,或者其他类中,注解里要设置类
public Object call(BlockException ex) {
return "限流";
}
业务:
@SentinelResource(value = "call", blockHandler = "call")
@GetMapping("test")
public Object test() {
return "ok";
}
2.根据异常数量进行降级:
@GetMapping("except")
public Object t(Integer id) {
Entry except = null;
try {
except = SphU.entry("except");
if (id != null) {
throw new RuntimeException();
}
} catch (DegradeException e) {
return e;
} catch (Exception e) {
Tracer.trace(e);
} finally {
if (except != null) {
except.exit();
}
}
return "ok";
}
@PostConstruct
public void rule() {
DegradeRule rule = new DegradeRule();
rule.setResource("except");
rule.setCount(2);
rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);
rule.setTimeWindow(61);
List<DegradeRule> rules = new ArrayList<>();
rules.add(rule);
DegradeRuleManager.loadRules(rules);
}
设想,如果使用到注解,那么在注解value是必须写的,这样资源名就写死了.如果有个公用方法,能不能想办法根据参数去更加细粒度的限流等其他操作呢;
其实只要在SentinelResourceAspect入手,这是个aop操作类,然后增加@SentinelResource注解参数,支持通过参数动态埋点,做到细粒度;