sentinel的官方文档:quick-start
首先搭建一个springboot项目,springboot的版本号要和spring-cloud的对应,在pom.xml中引入sentinel相关jar(文章最后有代码链接)
com.alibaba.cloud spring-cloud-alibaba-dependencies 2.2.8.RELEASE pom import com.alibaba.cloud spring-cloud-starter-alibaba-sentinel 2.2.8.RELEASE
springboot版本我用的和sentinel一样的版本:
org.springframework.boot spring-boot-starter-parent 2.2.8.RELEASE
然后在 application.properties 中设置端口和名称以及 映射到 控制台的地址:
spring.application.name=sentinel-test server.port=18083 spring.cloud.sentinel.transport.dashboard=localhost:8080
本地代码demo的目录及代码如下:
SentinelDemoApplication(默认的,不做修改): @SpringBootApplication public class SentinelDemoApplication { public static void main(String[] args) { SpringApplication.run(SentinelDemoApplication.class, args); } }
OrderController: @Controller @RequestMapping("/order") public class OrderController { //blockHandlerClass 和 blockHandler 设置被限流后 的处理方法和类,也可以不配置使用系统默认处理; @SentinelResource(value = "order_hello",blockHandler ="handleException",blockHandlerClass={ExceptionUtil.class}) @RequestMapping("/hello") @ResponseBody public String hello() throws InterruptedException{ System.out.println("接收到请求"); return "hello"; } }
ExceptionUtil: public class ExceptionUtil { public static String handleException(BlockException ex){ System.out.println("0ops:"+ex.getClass().getCanonicalName()); return "此方法被限流了"; } }
application.properties
spring.application.name=sentinel-test server.port=18083 spring.cloud.sentinel.transport.dashboard=localhost:8080
流控规则
下载 sentinel-dashboard.jar 后通过 cmd控制台 java -jar sentinel-dashboard.jar 运行
启动应用后 在 http://localhost:8080/ 能看到应用,在 流控规则 中 新增流控规则,流控规则中的资源名要和 方法上 @SentinelResource 的值 或 方法请求路径一样,如以下方法的资源名是 order_hello 或 /order/hello,如果方法上没有@SentinelResource这个注解,则流控规则无效;
新增 流控规则 后(我是用QPS:每秒钟能访问的次数),然后多次在浏览器输入http://localhost:18083/order/hello ,连续刷新多次能看到拦截效果
实时监控
demo和 sentinel-dashboard.jar 存放在网盘:
链接:https://pan.baidu.com/s/1eRSZ1rCg5ctA8RB4wl7z7w?pwd=8yb2
提取码:8yb2