什么网站教做医学实验报告,网页广告投放,做视频背景音乐网站,优化大师是什么意思前言#xff1a;作者查阅了Sentinel官网、51CTO、CSDN、码农家园、博客园等很多技术文章都没有很准确的springmvc集成Sentinel的示例#xff0c;因此整理了本文#xff0c;主要介绍SpringMvc集成Sentinel
SpringMvc集成Sentinel
一、Sentinel 介绍
随着微服务的流行…前言作者查阅了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
spring.version5.3.18/spring.version
servlet.api.version2.5/servlet.api.version sentinel.version1.8.6/sentinel.version
1、springmvc项目引入依赖pom !-- 这是sentinel的核心依赖 --dependencygroupIdcom.alibaba.csp/groupIdartifactIdsentinel-core/artifactIdversion${sentinel.version}/version/dependency!-- 这是将自己项目和sentinel-dashboard打通的依赖 --dependencygroupIdcom.alibaba.csp/groupIdartifactIdsentinel-transport-simple-http/artifactIdversion${sentinel.version}/version/dependency!-- 这是使用sentinel对限流资源进行AOP --dependencygroupIdcom.alibaba.csp/groupIdartifactIdsentinel-annotation-aspectj/artifactIdversion${sentinel.version}/version/dependency!--这是使用sentinel适配Web Servlet的依赖--dependencygroupIdcom.alibaba.csp/groupIdartifactIdsentinel-web-servlet/artifactIdversion${sentinel.version}/version/dependency!-- 这是使用sentinel热点参数限流功能依赖 --dependencygroupIdcom.alibaba.csp/groupIdartifactIdsentinel-parameter-flow-control/artifactIdversion${sentinel.version}/version/dependency
2、添加配置文件
在application.properties下创建同级文件sentinel.properties内容如下
# 集成到sentinel的项目名称
project.namespring-sentinel-demo
# 对应的sentinel-dashboard地址
csp.sentinel.dashboard.serverlocalhost:8080
3、添加配置类引入配置文件
创建配置类SentinelAspectConfiguration并引入配置文件sentinel.properties
import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;Configuration
PropertySources({PropertySource(classpath:/sentinel.properties)})
public class SentinelAspectConfiguration {Beanpublic SentinelResourceAspect sentinelResourceAspect() {return new SentinelResourceAspect();}
}
4、web.xml新增如下过滤器配置 filterfilter-nameSentinelCommonFilter/filter-namefilter-classcom.alibaba.csp.sentinel.adapter.servlet.CommonFilter/filter-class/filterfilter-mappingfilter-nameSentinelCommonFilter/filter-nameurl-pattern/*/url-pattern/filter-mapping
接入 filter 之后所有访问的 Web URL 就会被自动统计为 Sentinel 的资源—来源于 https://sentinelguard.io/zh-cn/docs/open-source-framework-integrations.html
开源框架适配的Web 适配下的Web Servlet
5、创建Controller接口
Controller
public class WebMvcTestController {GetMapping(/hello)ResponseBodypublic String apiHello(String id) {System.out.println(id id);Date date new Date();System.out.println(date date);return Hello!;}GetMapping(/doBusiness)ResponseBodypublic String doBusiness(String id) {System.out.println(doBusiness );return Oops...;}}
6、下载控制台-即图形化实时监控平台
参考 https://sentinelguard.io/zh-cn/docs/dashboard.html Sentinel 控制台的下载和启动
访问 https://github.com/alibaba/Sentinel/releases/tag/1.8.6 点击下载
7、运行控制台
java -Dserver.port8080 -Dcsp.sentinel.dashboard.serverlocalhost:8080 -Dproject.namesentinel-dashboard -jar sentinel-dashboard.jar 运行控制台后运行springmvc项目然后访问某一个路径就可以在控制台看到了实时监控如果这个路径没有被访问是显示不出来的 这个时候我们配置限流为即Qps为2 8、测试限流
这里我们用postman进行压测填写请求的路径保存。并点击run调出压测执行器 执行后查看结果如下 四、自定义异常返回
1、定义如下接口(这里只进行了常见的url定义方式的定义)
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;Controller
RequestMapping(/test)
public class WebMvcTestController {/*** 1.未配置流控规则 1000次请求没有间隔发起请求应该在1秒中完成09:44:33* param id* return*/RequestMapping(/RequestMapping)ResponseBodypublic String RequestMapping(String id) {return RequestMapping!;}GetMapping(/GetMapping)ResponseBodypublic String GetMapping(String id) {return GetMapping...;}PostMapping(/PostMapping)ResponseBodypublic String PostMapping(String id) {return PostMapping...;}/** 路径变量Path Variables使用花括号 {} 来标记路径中的变量并通过 PathVariable 注解将其绑定到方法参数上* */GetMapping(/GetMapping/{id})ResponseBodypublic String apiFoo(PathVariable(id) Long id) {return Hello id;}/** Ant风格的路径匹配* 使用 ? 表示任意单个字符* * 表示任意多个字符不包含路径分隔符 /* ** 表示任意多个字符包含路径分隔符 /。* */GetMapping(/Ant/*/{id})ResponseBodypublic String Ant(PathVariable(id) Long id) {return Ant id;}/** 正则表达式路径匹配使用 RequestMapping 注解的 value 属性结合正则表达式来定义请求路径。* */GetMapping(value /users/{id:\\d})ResponseBodypublic String pattern(PathVariable(id) int id) {return Ant id;}
}
2、自定义限流返回处理Handler
import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson.JSON;
import org.springframework.context.ApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.util.UrlPathHelper;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;public class SentinelExceptionHandler implements UrlBlockHandler {Overridepublic void blocked(HttpServletRequest request, HttpServletResponse httpServletResponse, BlockException e) throws IOException {String contextPath request.getContextPath();String servletPath request.getServletPath();String requestURI request.getRequestURI();String url request.getRequestURL().toString();System.out.println(servletPath servletPath);System.out.println(requestURI requestURI);System.out.println(url url);if (contextPath null) {contextPath ;}ApplicationContext controllerApplicationContext LiteFlowApplicationContext.getControllerApplicationContext();RequestMappingHandlerMapping handlerMapping controllerApplicationContext.getBean(RequestMappingHandlerMapping.class);// 查找匹配的处理方法Class? returnType null;MapRequestMappingInfo, HandlerMethod handlerMethods handlerMapping.getHandlerMethods();for (Map.EntryRequestMappingInfo, HandlerMethod entry : handlerMethods.entrySet()) {RequestMappingInfo requestMappingInfo entry.getKey();HandlerMethod handlerMethod entry.getValue();//匹配urlif (requestMappingInfo.getPatternsCondition().getPatterns().contains(requestURI)) {System.out.println(Controller: handlerMethod.getBeanType().getName());System.out.println(Method: handlerMethod.getMethod().getName());System.out.println(getReturnType: handlerMethod.getMethod().getReturnType());returnType handlerMethod.getMethod().getReturnType();break;}//匹配路径带参数的urlUrlPathHelper pathHelper new UrlPathHelper();String lookupPath pathHelper.getPathWithinApplication(request);PatternsRequestCondition patternsCondition requestMappingInfo.getPatternsCondition();if (patternsCondition ! null patternsCondition.getMatchingPatterns(lookupPath).size() 0) {System.out.println(Controller1111: handlerMethod.getBeanType().getName());System.out.println(Method111: handlerMethod.getMethod().getName());System.out.println(getReturnType: handlerMethod.getMethod().getReturnType());returnType handlerMethod.getMethod().getReturnType();break;}}httpServletResponse.setContentType(application/json;charsetutf-8);ResponseData data null;if (returnType ! null) {if (returnType String.class) {String str 返回类型为字符串方法限流;httpServletResponse.getWriter().write(str);return;} else if (returnType Integer.class) {httpServletResponse.getWriter().write(new Integer(1));return;} else if (returnType Long.class) {httpServletResponse.getWriter().write(2);return;} else if (returnType Double.class) {} else if (returnType Boolean.class) {} else if (returnType Float.class) {} else if (returnType Byte.class) {}}//BlockException 异常接口,包含Sentinel的五个异常// FlowException 限流异常// DegradeException 降级异常// ParamFlowException 参数限流异常// AuthorityException 授权异常// SystemBlockException 系统负载异常if (e instanceof FlowException) {data new ResponseData(-1, 流控规则被触发......);} else if (e instanceof DegradeException) {data new ResponseData(-2, 降级规则被触发...);} else if (e instanceof AuthorityException) {data new ResponseData(-3, 授权规则被触发...);} else if (e instanceof ParamFlowException) {data new ResponseData(-4, 热点规则被触发...);} else if (e instanceof SystemBlockException) {data new ResponseData(-5, 系统规则被触发...);}httpServletResponse.getWriter().write(JSON.toJSONString(data));}
}
3、使用自定义限流处理类
import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager;
import org.springframework.context.annotation.Configuration;Configuration
public class SentinelConfig {public SentinelConfig() {WebCallbackManager.setUrlBlockHandler(new SentinelExceptionHandler());}
}
4、配置限流并测试结果
当开启限流后访问触发自定义UrlBlockHandler后结果如下 访问对应得url后控制台打印
servletPath /test/RequestMapping
requestURI /test/RequestMapping
url http://localhost:8081/test/RequestMapping
Controller: org.example.WebMvcTestController
Method: RequestMapping
getReturnType: class java.lang.String
servletPath /test/GetMapping
requestURI /test/GetMapping
url http://localhost:8081/test/GetMapping
Controller: org.example.WebMvcTestController
Method: GetMapping
getReturnType: class java.lang.String
servletPath /test/PostMapping
requestURI /test/PostMapping
url http://localhost:8081/test/PostMapping
Controller: org.example.WebMvcTestController
Method: PostMapping
getReturnType: class java.lang.String
servletPath /test/GetMapping/4
requestURI /test/GetMapping/4
url http://localhost:8081/test/GetMapping/4
Controller1111: org.example.WebMvcTestController
Method111: apiFoo
getReturnType: class java.lang.String
servletPath /test/Ant/a/5
requestURI /test/Ant/a/5
url http://localhost:8081/test/Ant/a/5
Controller1111: org.example.WebMvcTestController
Method111: Ant
getReturnType: class java.lang.String
servletPath /test/users/5
requestURI /test/users/5
url http://localhost:8081/test/users/5
Controller1111: org.example.WebMvcTestController
Method111: pattern
getReturnType: class java.lang.String
5、页面效果如下 五、springboot集成Sentinel
因为springboot集成文章较多这里不多做赘述
Sentinel 与 Spring Boot/Spring Cloud 的整合见 Sentinel Spring Cloud Starter。 作者京东健康 马仁喜 来源京东云开发者社区 转载请注明来源
文章转载自: http://www.morning.heleyo.com.gov.cn.heleyo.com http://www.morning.zlkps.cn.gov.cn.zlkps.cn http://www.morning.dxpqd.cn.gov.cn.dxpqd.cn http://www.morning.xcszl.cn.gov.cn.xcszl.cn http://www.morning.yckrm.cn.gov.cn.yckrm.cn http://www.morning.xxrgt.cn.gov.cn.xxrgt.cn http://www.morning.qyhcm.cn.gov.cn.qyhcm.cn http://www.morning.ypjjh.cn.gov.cn.ypjjh.cn http://www.morning.fdfdz.cn.gov.cn.fdfdz.cn http://www.morning.synkr.cn.gov.cn.synkr.cn http://www.morning.pcrzf.cn.gov.cn.pcrzf.cn http://www.morning.xpmhs.cn.gov.cn.xpmhs.cn http://www.morning.fqzz3.cn.gov.cn.fqzz3.cn http://www.morning.ypqwm.cn.gov.cn.ypqwm.cn http://www.morning.lmbm.cn.gov.cn.lmbm.cn http://www.morning.wdshp.cn.gov.cn.wdshp.cn http://www.morning.kbqws.cn.gov.cn.kbqws.cn http://www.morning.rdmn.cn.gov.cn.rdmn.cn http://www.morning.rfjmy.cn.gov.cn.rfjmy.cn http://www.morning.srjbs.cn.gov.cn.srjbs.cn http://www.morning.xprq.cn.gov.cn.xprq.cn http://www.morning.nnwnl.cn.gov.cn.nnwnl.cn http://www.morning.ggfdq.cn.gov.cn.ggfdq.cn http://www.morning.clkyw.cn.gov.cn.clkyw.cn http://www.morning.bfnbn.cn.gov.cn.bfnbn.cn http://www.morning.zqcdl.cn.gov.cn.zqcdl.cn http://www.morning.jnzfs.cn.gov.cn.jnzfs.cn http://www.morning.zljqb.cn.gov.cn.zljqb.cn http://www.morning.wkmpx.cn.gov.cn.wkmpx.cn http://www.morning.stbhn.cn.gov.cn.stbhn.cn http://www.morning.mwmtk.cn.gov.cn.mwmtk.cn http://www.morning.bpmdx.cn.gov.cn.bpmdx.cn http://www.morning.fbpyd.cn.gov.cn.fbpyd.cn http://www.morning.lxqkt.cn.gov.cn.lxqkt.cn http://www.morning.lwyqd.cn.gov.cn.lwyqd.cn http://www.morning.ylpl.cn.gov.cn.ylpl.cn http://www.morning.lrnfn.cn.gov.cn.lrnfn.cn http://www.morning.jggr.cn.gov.cn.jggr.cn http://www.morning.gpkjx.cn.gov.cn.gpkjx.cn http://www.morning.mzcsp.cn.gov.cn.mzcsp.cn http://www.morning.yixingshengya.com.gov.cn.yixingshengya.com http://www.morning.zqsnj.cn.gov.cn.zqsnj.cn http://www.morning.fbrshjf.com.gov.cn.fbrshjf.com http://www.morning.ntqqm.cn.gov.cn.ntqqm.cn http://www.morning.ympcj.cn.gov.cn.ympcj.cn http://www.morning.mxbks.cn.gov.cn.mxbks.cn http://www.morning.lbzgt.cn.gov.cn.lbzgt.cn http://www.morning.ljzqb.cn.gov.cn.ljzqb.cn http://www.morning.ssxlt.cn.gov.cn.ssxlt.cn http://www.morning.jqlx.cn.gov.cn.jqlx.cn http://www.morning.pzcqz.cn.gov.cn.pzcqz.cn http://www.morning.fgkwh.cn.gov.cn.fgkwh.cn http://www.morning.xphcg.cn.gov.cn.xphcg.cn http://www.morning.pxspq.cn.gov.cn.pxspq.cn http://www.morning.sqskm.cn.gov.cn.sqskm.cn http://www.morning.nrzbq.cn.gov.cn.nrzbq.cn http://www.morning.qpqb.cn.gov.cn.qpqb.cn http://www.morning.roymf.cn.gov.cn.roymf.cn http://www.morning.yrdn.cn.gov.cn.yrdn.cn http://www.morning.jrplk.cn.gov.cn.jrplk.cn http://www.morning.gsksm.cn.gov.cn.gsksm.cn http://www.morning.trkhx.cn.gov.cn.trkhx.cn http://www.morning.fdsbs.cn.gov.cn.fdsbs.cn http://www.morning.tpyjr.cn.gov.cn.tpyjr.cn http://www.morning.bnrff.cn.gov.cn.bnrff.cn http://www.morning.qsbcg.cn.gov.cn.qsbcg.cn http://www.morning.xmnlc.cn.gov.cn.xmnlc.cn http://www.morning.qyjqj.cn.gov.cn.qyjqj.cn http://www.morning.wtcyz.cn.gov.cn.wtcyz.cn http://www.morning.rswfj.cn.gov.cn.rswfj.cn http://www.morning.pphbn.cn.gov.cn.pphbn.cn http://www.morning.qblcm.cn.gov.cn.qblcm.cn http://www.morning.pbmkh.cn.gov.cn.pbmkh.cn http://www.morning.glcgy.cn.gov.cn.glcgy.cn http://www.morning.njqpg.cn.gov.cn.njqpg.cn http://www.morning.nqwz.cn.gov.cn.nqwz.cn http://www.morning.flxgx.cn.gov.cn.flxgx.cn http://www.morning.dkqyg.cn.gov.cn.dkqyg.cn http://www.morning.gklxm.cn.gov.cn.gklxm.cn http://www.morning.rqlbp.cn.gov.cn.rqlbp.cn