前言
前几天ali开源了Sentinel项目,Sentinel中文意思是哨兵,作为dubbo的配套项目,看字面意思是dubbo的一个监控系统,sentinel自己的官方文档上是这样说的:Sentinel 以流量为切入点,从流量控制、熔断降级、系统负载保护等多个维度保护服务的稳定性。本文就是想简单的配置一下sentinel。
准备
Sentinel的官方文档是放在 ,配合上一篇文章配置的dubbo项目,无需依赖其他的外部资源。
开始
在provider端的 pom.xml
文件中加入以下依赖:
com.alibaba.csp sentinel-core 0.1.1
在sayHello服务的中嵌入Sentinel的代码:
public class SayHelloImpl implements SayHello { @Override public String sayHello(String name) { initFlowRules(); Entry entry = null; try { entry = SphU.entry("HelloWorld"); System.out.println("hello world"); return "Hello " + name; } catch (BlockException e1) { System.out.println("exception is " + BlockException.isBlockException(e1)); System.out.println("block!"); } finally { if (entry != null) { entry.exit(); } } return ""; } private void initFlowRules() { Listrules = new ArrayList (); FlowRule rule = new FlowRule(); rule.setResource("HelloWorld"); rule.setGrade(RuleConstant.FLOW_GRADE_QPS); // Set limit QPS to 20. rule.setCount(5); rules.add(rule); FlowRuleManager.loadRules(rules); }}
在上述代码中,把限流的方式设置为QPS = 5,然后改造下客户端的代码,进行20 次的调用:
public class ConsumerApplication { public static void main(String[] args) { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); SayHello sayHello = (SayHello) ctx.getBean("sayHello"); for (int i = 0; i < 20; i++) { String s = sayHello.sayHello("张三"); System.out.println(i + ":" + s); } }}
启动Provider端和Consumer端后,看到provider的后台打印的是:
hello worldhello worldhello worldhello worldhello worldexception is trueblock!exception is trueblock!exception is trueblock!exception is trueblock!exception is trueblock!exception is trueblock!exception is trueblock!exception is trueblock!exception is trueblock!exception is trueblock!exception is trueblock!exception is trueblock!exception is trueblock!exception is trueblock!exception is trueblock!
只有前五次的调用成功了,其他的都在报了BlockException。所以在限流的时候,可以通过在BlockException 中进行限流那些请求的访问逻辑处理。
Sentinel其实有提供一套注解,实现代码零侵入,接下来把代码改成注解形式实现,增加Sentinel的注解依赖包:
com.alibaba.csp sentinel-annotation-aspectj 0.1.1
启动类改成springboot启动,增加注解的启动配置:
@SpringBootApplicationpublic class ProviderApplication { public static void main(String[] args) throws IOException { SpringApplication.run(ProviderApplication.class,args); System.in.read(); } @Bean public SentinelResourceAspect sentinelResourceAspect() { return new SentinelResourceAspect(); } @Bean public RegistryConfig registryConfig() { RegistryConfig registryConfig = new RegistryConfig(); registryConfig.setAddress("zookeeper://127.0.0.1:2181"); registryConfig.setClient("provider"); return registryConfig; }}