SpringMvc集成开源流量监控、限流、熔断降级、负载保护组件Sentinel ...

打印 上一主题 下一主题

主题 874|帖子 874|积分 2622

前言:作者查阅了Sentinel官网、51CTO、CSDN、码农家园、博客园等很多技术文章都没有很准确的springmvc集成Sentinel的示例,因此整理了本文,主要介绍SpringMvc集成Sentinel
SpringMvc集成Sentinel

一、Sentinel 介绍

随着微服务的流行,服务和服务之间的稳定性变得越来越重要。Sentinel 是面向分布式、多语言异构化服务架构的流量治理组件,主要以流量为切入点,从流量路由、流量控制、流量整形、熔断降级、系统自适应过载保护、热点流量防护等多个维度来帮助开发者保障微服务的稳定性。
GitHub主页:https://github.com/alibaba/Sentinel
中文文档:https://sentinelguard.io/zh-cn/docs/introduction.html
控制台文档:https://sentinelguard.io/zh-cn/docs/dashboard.html
核心类解析:https://github.com/alibaba/Sentinel/wiki/Sentinel-核心类解析
Sentinel示例项目:https://github.com/alibaba/Sentinel/tree/master/sentinel-demo
https://github.com/alibaba/spring-cloud-alibaba/tree/master/spring-cloud-alibaba-examples/sentinel-example
二、Sentinel 基本概念

资源

资源是 Sentinel 的关键概念。它可以是 Java 应用程序中的任何内容,例如,由应用程序提供的服务,或由应用程序调用的其它应用提供的服务,甚至可以是一段代码。在接下来的文档中,我们都会用资源来描述代码块。
只要通过 Sentinel API 定义的代码,就是资源,能够被 Sentinel 保护起来。大部分情况下,可以使用方法签名,URL,甚至服务名称作为资源名来标示资源。
规则

围绕资源的实时状态设定的规则,可以包括流量控制规则、熔断降级规则以及系统保护规则。所有规则可以动态实时调整。
三、springMVC集成Sentinel

这里用的是spring
5.3.18
2.5 1.8.6
1、springmvc项目引入依赖pom
  1.         
  2.         <dependency>
  3.             <groupId>com.alibaba.csp</groupId>
  4.             <artifactId>sentinel-core</artifactId>
  5.             <version>${sentinel.version}</version>
  6.         </dependency>
  7.         
  8.         <dependency>
  9.             <groupId>com.alibaba.csp</groupId>
  10.             <artifactId>sentinel-transport-simple-http</artifactId>
  11.             <version>${sentinel.version}</version>
  12.         </dependency>
  13.         
  14.         <dependency>
  15.             <groupId>com.alibaba.csp</groupId>
  16.             <artifactId>sentinel-annotation-aspectj</artifactId>
  17.             <version>${sentinel.version}</version>
  18.         </dependency>
  19.         
  20.         <dependency>
  21.             <groupId>com.alibaba.csp</groupId>
  22.             <artifactId>sentinel-web-servlet</artifactId>
  23.             <version>${sentinel.version}</version>
  24.         </dependency>
  25.         
  26.         <dependency>
  27.             <groupId>com.alibaba.csp</groupId>
  28.             <artifactId>sentinel-parameter-flow-control</artifactId>
  29.             <version>${sentinel.version}</version>
  30.         </dependency>
复制代码
2、添加配置文件

在application.properties下创建同级文件sentinel.properties,内容如下
  1. # 集成到sentinel的项目名称
  2. project.name=spring-sentinel-demo
  3. # 对应的sentinel-dashboard地址
  4. csp.sentinel.dashboard.server=localhost:8080
复制代码
3、添加配置类引入配置文件

创建配置类SentinelAspectConfiguration并引入配置文件sentinel.properties
  1. import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.context.annotation.PropertySource;
  5. import org.springframework.context.annotation.PropertySources;
  6. @Configuration
  7. @PropertySources({@PropertySource("classpath:/sentinel.properties")})
  8. public class SentinelAspectConfiguration {
  9.     @Bean
  10.     public SentinelResourceAspect sentinelResourceAspect() {
  11.         return new SentinelResourceAspect();
  12.     }
  13. }
复制代码
4、web.xml新增如下过滤器配置
  1. <filter>
  2.         <filter-name>SentinelCommonFilter</filter-name>
  3.         <filter-class>com.alibaba.csp.sentinel.adapter.servlet.CommonFilter</filter-class>
  4.     </filter>
  5.     <filter-mapping>
  6.         <filter-name>SentinelCommonFilter</filter-name>
  7.         <url-pattern>/*</url-pattern>
  8.     </filter-mapping>
复制代码
接入 filter 之后,所有访问的 Web URL 就会被自动统计为 Sentinel 的资源---来源于 https://sentinelguard.io/zh-cn/docs/open-source-framework-integrations.html
开源框架适配的Web 适配下的Web Servlet
5、创建Controller接口
  1. @Controller
  2. public class WebMvcTestController {
  3.     @GetMapping("/hello")
  4.     @ResponseBody
  5.     public String apiHello(String id) {
  6.         System.out.println("id = " + id);
  7.         Date date = new Date();
  8.         System.out.println("date = " + date);
  9.         return "Hello!";
  10.     }
  11.     @GetMapping("/doBusiness")
  12.     @ResponseBody
  13.     public String doBusiness(String id) {
  14.         System.out.println("doBusiness = ");
  15.         return "Oops...";
  16.     }
  17. }
复制代码
6、下载控制台-即图形化实时监控平台

参考 https://sentinelguard.io/zh-cn/docs/dashboard.html Sentinel 控制台的下载和启动
访问 https://github.com/alibaba/Sentinel/releases/tag/1.8.6

点击下载
7、运行控制台
  1. java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard.jar
复制代码

运行控制台后运行springmvc项目,然后访问某一个路径,就可以在控制台看到了,实时监控如果这个路径没有被访问是显示不出来的

这个时候我们配置限流为即Qps为2

8、测试限流

这里我们用postman进行压测,填写请求的路径保存。并点击run调出压测执行器

执行后查看结果如下

四、自定义异常返回

1、定义如下接口(这里只进行了常见的url定义方式的定义)
  1. import org.springframework.stereotype.Controller;
  2. import org.springframework.web.bind.annotation.*;
  3. @Controller
  4. @RequestMapping("/test")
  5. public class WebMvcTestController {
  6.   
  7.     /**
  8.      * 1.未配置流控规则 1000次请求没有间隔发起请求,应该在1秒中完成09:44:33
  9.      * @param id
  10.      * @return
  11.      */
  12.     @RequestMapping("/RequestMapping")
  13.     @ResponseBody
  14.     public String RequestMapping(String id) {
  15.         return "RequestMapping!";
  16.     }
  17.     @GetMapping("/GetMapping")
  18.     @ResponseBody
  19.     public String GetMapping(String id) {
  20.         return "GetMapping...";
  21.     }
  22.     @PostMapping("/PostMapping")
  23.     @ResponseBody
  24.     public String PostMapping(String id) {
  25.         return "PostMapping...";
  26.     }
  27.     /*
  28.     * 路径变量(Path Variables):使用花括号 {} 来标记路径中的变量,并通过 @PathVariable 注解将其绑定到方法参数上
  29.     * */
  30.     @GetMapping("/GetMapping/{id}")
  31.     @ResponseBody
  32.     public String apiFoo(@PathVariable("id") Long id) {
  33.         return "Hello " + id;
  34.     }
  35.     /*
  36.     * Ant风格的路径匹配:
  37.     *   使用 ? 表示任意单个字符,
  38.     *   * 表示任意多个字符(不包含路径分隔符 /),
  39.     *   ** 表示任意多个字符(包含路径分隔符 /)。
  40.     * */
  41.     @GetMapping("/Ant/*/{id}")
  42.     @ResponseBody
  43.     public String Ant(@PathVariable("id") Long id) {
  44.         return "Ant " + id;
  45.     }
  46.     /*
  47.     * 正则表达式路径匹配:使用 @RequestMapping 注解的 value 属性结合正则表达式来定义请求路径。
  48.     * */
  49.     @GetMapping(value = "/users/{id:\\d+}")
  50.     @ResponseBody
  51.     public String pattern(@PathVariable("id") int id) {
  52.         return "Ant " + id;
  53.     }
  54. }
复制代码
2、自定义限流返回处理Handler
  1. import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
  2. import com.alibaba.csp.sentinel.slots.block.BlockException;
  3. import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
  4. import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
  5. import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
  6. import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
  7. import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
  8. import com.alibaba.fastjson.JSON;
  9. import org.springframework.context.ApplicationContext;
  10. import org.springframework.web.method.HandlerMethod;
  11. import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
  12. import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
  13. import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
  14. import org.springframework.web.util.UrlPathHelper;
  15. import javax.servlet.http.HttpServletRequest;
  16. import javax.servlet.http.HttpServletResponse;
  17. import java.io.IOException;
  18. import java.util.*;
  19. public class SentinelExceptionHandler implements UrlBlockHandler {
  20.     @Override
  21.     public void blocked(HttpServletRequest request, HttpServletResponse httpServletResponse, BlockException e) throws IOException {
  22.         String contextPath = request.getContextPath();
  23.         String servletPath = request.getServletPath();
  24.         String requestURI = request.getRequestURI();
  25.         String url = request.getRequestURL().toString();
  26.         System.out.println("servletPath = " + servletPath);
  27.         System.out.println("requestURI = " + requestURI);
  28.         System.out.println("url = " + url);
  29.         if (contextPath == null) {
  30.             contextPath = "";
  31.         }
  32.         ApplicationContext controllerApplicationContext = LiteFlowApplicationContext.getControllerApplicationContext();
  33.         RequestMappingHandlerMapping handlerMapping = controllerApplicationContext.getBean(RequestMappingHandlerMapping.class);
  34.         // 查找匹配的处理方法
  35.         Class<?> returnType = null;
  36.         Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();
  37.         for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : handlerMethods.entrySet()) {
  38.             RequestMappingInfo requestMappingInfo = entry.getKey();
  39.             HandlerMethod handlerMethod = entry.getValue();
  40.             //匹配url
  41.             if (requestMappingInfo.getPatternsCondition().getPatterns().contains(requestURI)) {
  42.                 System.out.println("Controller: " + handlerMethod.getBeanType().getName());
  43.                 System.out.println("Method: " + handlerMethod.getMethod().getName());
  44.                 System.out.println("getReturnType: " + handlerMethod.getMethod().getReturnType());
  45.                 returnType = handlerMethod.getMethod().getReturnType();
  46.                 break;
  47.             }
  48.             //匹配路径带参数的url
  49.             UrlPathHelper pathHelper = new UrlPathHelper();
  50.             String lookupPath = pathHelper.getPathWithinApplication(request);
  51.             PatternsRequestCondition patternsCondition = requestMappingInfo.getPatternsCondition();
  52.             if (patternsCondition != null && patternsCondition.getMatchingPatterns(lookupPath).size() > 0) {
  53.                 System.out.println("Controller1111: " + handlerMethod.getBeanType().getName());
  54.                 System.out.println("Method111: " + handlerMethod.getMethod().getName());
  55.                 System.out.println("getReturnType: " + handlerMethod.getMethod().getReturnType());
  56.                 returnType = handlerMethod.getMethod().getReturnType();
  57.                 break;
  58.             }
  59.         }
  60.         httpServletResponse.setContentType("application/json;charset=utf-8");
  61.         ResponseData data = null;
  62.         if (returnType != null) {
  63.             if (returnType == String.class) {
  64.                 String str = "返回类型为字符串方法限流";
  65.                 httpServletResponse.getWriter().write(str);
  66.                 return;
  67.             } else if (returnType == Integer.class) {
  68.                 httpServletResponse.getWriter().write(new Integer(1));
  69.                 return;
  70.             } else if (returnType == Long.class) {
  71.                 httpServletResponse.getWriter().write(2);
  72.                 return;
  73.             } else if (returnType == Double.class) {
  74.             } else if (returnType == Boolean.class) {
  75.             } else if (returnType == Float.class) {
  76.             } else if (returnType == Byte.class) {
  77.             }
  78.         }
  79.         //BlockException 异常接口,包含Sentinel的五个异常
  80.         // FlowException 限流异常
  81.         // DegradeException 降级异常
  82.         // ParamFlowException 参数限流异常
  83.         // AuthorityException 授权异常
  84.         // SystemBlockException 系统负载异常
  85.         if (e instanceof FlowException) {
  86.             data = new ResponseData(-1, "流控规则被触发......");
  87.         } else if (e instanceof DegradeException) {
  88.             data = new ResponseData(-2, "降级规则被触发...");
  89.         } else if (e instanceof AuthorityException) {
  90.             data = new ResponseData(-3, "授权规则被触发...");
  91.         } else if (e instanceof ParamFlowException) {
  92.             data = new ResponseData(-4, "热点规则被触发...");
  93.         } else if (e instanceof SystemBlockException) {
  94.             data = new ResponseData(-5, "系统规则被触发...");
  95.         }
  96.         httpServletResponse.getWriter().write(JSON.toJSONString(data));
  97.     }
  98. }
复制代码
3、使用自定义限流处理类
  1. import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager;
  2. import org.springframework.context.annotation.Configuration;
  3. @Configuration
  4. public class SentinelConfig {
  5.     public SentinelConfig() {
  6.         WebCallbackManager.setUrlBlockHandler(new SentinelExceptionHandler());
  7.     }
  8. }
复制代码
4、配置限流并测试结果

当开启限流后访问触发自定义UrlBlockHandler后结果如下

访问对应得url后控制台打印
  1. servletPath = /test/RequestMapping
  2. requestURI = /test/RequestMapping
  3. url = http://localhost:8081/test/RequestMapping
  4. Controller: org.example.WebMvcTestController
  5. Method: RequestMapping
  6. getReturnType: class java.lang.String
  7. servletPath = /test/GetMapping
  8. requestURI = /test/GetMapping
  9. url = http://localhost:8081/test/GetMapping
  10. Controller: org.example.WebMvcTestController
  11. Method: GetMapping
  12. getReturnType: class java.lang.String
  13. servletPath = /test/PostMapping
  14. requestURI = /test/PostMapping
  15. url = http://localhost:8081/test/PostMapping
  16. Controller: org.example.WebMvcTestController
  17. Method: PostMapping
  18. getReturnType: class java.lang.String
  19. servletPath = /test/GetMapping/4
  20. requestURI = /test/GetMapping/4
  21. url = http://localhost:8081/test/GetMapping/4
  22. Controller1111: org.example.WebMvcTestController
  23. Method111: apiFoo
  24. getReturnType: class java.lang.String
  25. servletPath = /test/Ant/a/5
  26. requestURI = /test/Ant/a/5
  27. url = http://localhost:8081/test/Ant/a/5
  28. Controller1111: org.example.WebMvcTestController
  29. Method111: Ant
  30. getReturnType: class java.lang.String
  31. servletPath = /test/users/5
  32. requestURI = /test/users/5
  33. url = http://localhost:8081/test/users/5
  34. Controller1111: org.example.WebMvcTestController
  35. Method111: pattern
  36. getReturnType: class java.lang.String
复制代码
5、页面效果如下


五、springboot集成Sentinel

因为springboot集成文章较多,这里不多做赘述
Sentinel 与 Spring Boot/Spring Cloud 的整合见 Sentinel Spring Cloud Starter
作者:京东健康 马仁喜
来源:京东云开发者社区 转载请注明来源

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

花瓣小跑

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表