1: 添加依赖
<dependency> <groupId>com.alibaba.csp</groupId> <artifactId>sentinel-dubbo-adapter</artifactId> <version>1.6.3</version> </dependency>
2: 服务端 启动之前 添加限流规则 @SpringBootApplication public class SentinelProviderApplication { public static void main(String[] args) { init();// 在启动之前 开启限流规则 SpringApplication.run(SentinelProviderApplication.class, args); } public static void init() { FlowRule flowRule=new FlowRule(); //创建限流规则 flowRule.setResource("com.gupao.SentinelService:SayHello(java.lang.String)");// 添加接口全路径 和参数类型 flowRule.setCount(10);//限流的大小 10个 flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);// 限制qbs或者线程数 flowRule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);// 有均速限流 和梯度上升 //flowRule.setLimitApp("sentinel-web");//(设置限流来源)只拦截 sentinel-web 这个应用的请求 FlowRuleManager.loadRules(Collections.singletonList(flowRule)); //添加规则到FlowRuleManager里 } }
3: 设置了限流来源
如果服务端 设置了限流来源 //flowRule.setLimitApp("sentinel-web");//(设置限流来源)只拦截 sentinel-web 这个应用的请求
客户端需要 配置来源名称 sentinel-web
@GetMapping(value = "/say") public String say(){ // 限流的 来源 设置 来源名称 后端服务器 根据sentinel-web 进行拦截 RpcContext.getContext().setAttachment("dubboApplication","sentinel-web"); return SentinelService.SayHello("test"); }