1.添加依赖
<!-- dubbo --> <!-- Sentinel --> <dependency> <groupId>com.alibaba.csp</groupId> <artifactId>sentinel-dubbo-adapter</artifactId> <version>1.8.2</version> </dependency> <dependency> <groupId>com.alibaba.csp</groupId> <artifactId>sentinel-transport-simple-http</artifactId> <version>1.8.2</version> </dependency> <!-- controller的限流 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> <version>0.2.2.RELEASE</version> </dependency>
2.添加启动参数
-Djava.net.preferIPv4Stack=true -Dcsp.sentinel.api.port=8720 //指定客户端监控 API 的端口 -Dcsp.sentinel.dashboard.server=localhost:8080
3.全局限流返回
// 作为消费者,设置消费限流的返回 DubboAdapterGlobalConfig.setConsumerFallback(new DubboFallback() { @Override public Result handle(Invoker<?> invoker, Invocation invocation, BlockException ex) { return new RpcResult("服务器处理不过来了,停下来休息休息"); } }); //controller 限流返回 WebCallbackManager.setUrlBlockHandler(new UrlBlockHandler() { @Override public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException ex) throws IOException { response.setCharacterEncoding("utf-8"); response.setContentType("application/json;charset=utf-8"); Map<String, Object> map = new HashMap<>(16); map.put("rspCode", "0001"); map.put("rspMsg", "限流了"); response.getWriter().write(JSON.toJSONString(map)); } });
4.注解支持的配置Bean
// 注解支持的配置Bean @Bean public SentinelResourceAspect sentinelResourceAspect() { return new SentinelResourceAspect(); }
自己看得懂系列,有问题可以私信我