SENTINEL 熔断限流降级框架
在学习sentinel之前我已经玩过hystrix了,看到nacos真的就感觉不需要这边引用一个框架!这边又换一个!对于初学者算友好!就是一些配置。首先如果我们只是想,先搭建一个sentinel看看样!我导入了
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-core</artifactId>
<version>1.7.0</version>
</dependency>
然后你就可以导入
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-annotation-aspectj</artifactId>
<version>1.7.1</version>
</dependency>
来注解 @SentinelResource(value=“rule”,blockhandler=“method”) 记得写个method来降级回调。
/**
* 定义限流规则
*/
@PostConstruct
private void initFlowRules(){
List<FlowRule> rules = new ArrayList<>();
FlowRule rule = new FlowRule();
rule.setResource("HelloWorld");
rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
// 设置QPS为1
rule.setCount(1);
rules.add(rule);
FlowRuleManager.loadRules(rules);
}
还得定义sentinel的限流规则。之后可以在sentinel dashboard中直接鼠标操作。
参考:
@RequestMapping("/getOrder1")
@ResponseBody
public String queryOrder2(@RequestParam("orderId") String orderId) {
Entry entry = null;
// 资源名 也就是规则名
String resourceName = "KEY";
try {
// entry可以理解成入口登记
entry = SphU.entry(resourceName);
// 被保护的逻辑, 这里为订单查询接口
return orderQueryService.queryOrderInfo(orderId);
} catch (BlockException blockException) {
// 接口被限流的时候, 会进入到这里
LOG.warn("---getOrder1接口被限流了---, exception: ", blockException);
return "接口限流, 返回空";
} finally {
// SphU.entry(xxx) 需要与 entry.exit() 成对出现,否则会导致调用链记录异常
if (entry != null) {
entry.exit();
}
}
}
然后限流就差不多了。
补充一句,在.yml中 写入eager这个便可以启动项目在dashboard中
具体看此博客NACOS:SENTINEL DASHBOARD 的配置