赞
踩
本文档需要配合文末项目案例阅读
Sentinel主要用于对接口或方法访问进行限流、熔断降级等功能,自带前端控制台,支持对流控、熔断等规则实时修改。
不使用前端控制台,直接在项目中使用
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
@Configuration public class SentinelConfig{ @Bean public SentinelResourceAspect sentinelResourceAspect() { return new SentinelResourceAspect(); } @PostConstruct private void initRules() { //=============================规则1========================= MyFlowRule rule1 = new MyFlowRule(); rule1.setResource("rule1");//规则名称 rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);//如果设置0则按照线程数限流,如果设置1则按照QPS(每秒查询率)限流 rule1.setCount(10); // 每秒调用最大次数为 10 次 rule1.setControlBehavior(2)//0快速失败,1预警,2排队等候 rule1.setMaxQueueingTimeMs(1000);//排队超时阈值 //还有其他规则可在官网查看 //=============================规则2========================= MyFlowRule rule2 = new MyFlowRule(); rule2.setResource("rule2"); rule2.setGrade(RuleConstant.FLOW_GRADE_QPS); rule2.setCount(10); // 每秒调用最大次数为 10 次 List<FlowRule> rules = new ArrayList<>(); rules.add(rule1); rules.add(rule2); // 将控制规则载入到 Sentinel FlowRuleManager.loadRules(rules); } }
在需要限流的方法上添加 @SentinelResource(…) 注解
@Service public class DubboProviderServiceImpl implements DubboService{ @Override @SentinelResource(value = "rule1",blockHandler = "sentinelBlockHandler") public String dubboMethod(String s,int i) { return "provider1" + ":" + s+":"+ i; } public String sentinelFallback(String s,int i) { return "hello fallback"; } public String sentinelBlockHandler(String s, int i, BlockException blockException) { return "hello BlockHandler"; } }
注解参数:
value:配置类中的规则名称,上面代码用的"rule1"规则,每秒钟限制10次访问,
超过10次则默认快速失败即抛出异常
或
设置排队等候即上述配置类中的
rule1.setControlBehavior(2)
rule1.setMaxQueueingTimeMs(1000);
如果排队超时也会抛出异常
@SentinelResource(…) 注解添加以下参数
fallback:执行降级代码的方法名,降级方法注意与原方法参数相同,默认与原方法同一类中,也可以添加fallbackClass参数,将降级方法写在其它类中
blockHandler:也是执行降级代码的方法名,降级方法注意与原方法参数相同并增加BlockException blockException参数,默认与原方法同一类中,也可以添加blockHandlerClass参数,将降级方法写在其它类中。
两者区别:
fallback执行原因:是因 原方法 发生异常导致的降级,也是最后的防线。
blockHandler执行原因:是因为 原方法 被限流导致的降级
下载链接:https://github.com/alibaba/Sentinel/releases
将下载好的控制台jar包放在本地或者上传到虚拟机服务器上,执行启动命令
java -jar -Dserver.port=8080 sentinel-dashboard-1.8.2.jar
注意端口的修改和jar包名称是否正确
浏览器访问控制台部署的ip:port进入控制台页面,账号密码默认都是sentinel
登陆后,第一次创建都是空白的,左边两个是我使用过的
限流应用的配置文件添加
spring:
cloud:
sentinel:
transport:
dashboard: localhost:7000
port: 8719
#eager: true
第一个是控制台地址
第二个port:当一个服务器部署多个应用时要配置不同port,单个应用可忽略
项目启动并被访问后,前端会生成项目中配置的规则信息(如果没有,多刷新几次)
可以按需求编辑,等几秒配置就会生效
以上就是Sentinel的基本使用,其他功能也很简单,配合后文项目实例把每个选项配置一下就清楚了。
源码地址:https://download.csdn.net/download/weixin_45864962/69423084
下载后需要配置zookeeper
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。