Sentinel入门(一) Sentinel在Dubbo的实现

本文介绍了Sentinel在Dubbo项目中的实践,包括Consumer和Provider端的Sentinel Filter实现,详细阐述了资源名的生成以及EntryType的使用。通过示例展示了Sentinel如何进行流量控制,并探讨了其内部实现原理。
摘要由CSDN通过智能技术生成

Demo

Consumer.java

public static void main(String[] args) {
   

		FlowRule flowRule = new FlowRule();
		flowRule.setResource(
				"com.alibaba.cloud.examples.FooService:hello(java.lang.String)");
		// 设置1s内只能调用10次
        flowRule.setCount(10);
		flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
		flowRule.setLimitApp("default");
        // 注册限流规则
		FlowRuleManager.loadRules(Collections.singletonList(flowRule));

		SpringApplicationBuilder consumerBuilder = new SpringApplicationBuilder();
		ApplicationContext applicationContext = consumerBuilder
				.web(WebApplicationType.NONE).sources(SentinelDubboConsumerApp.class)
				.run(args);

		FooServiceConsumer service = applicationContext.getBean(FooServiceConsumer.class);
        // 测试调用15次,期望应该是有5调用失败的
		for (int i = 0; i < 15; i++) {
   
			try {
   
				String message = service.hello("Jim");
				System.out.println((i + 1) + " -> Success: " + message);
			}
			catch (SentinelRpcException ex) {
   
				System.out.println("Blocked");
			}
			catch (Exception ex) {
   
				ex.printStackTrace();
			}
		}
	}

FooService服务在Sentinel下对应的资源名是 com.alibaba.cloud.examples.FooService:hello(java.lang.String) 。详细见下面的Filter的getResourceName, 定义该资源名对应的限流规则:

 public static String getResourceName(Invoker<?> invoker, Invocation invocation) {
   
        StringBuilder buf = new StringBuilder(64);
        buf.append(invoker.getInterface().getName()
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值