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()