作者查閱了Sentinel官網、51CTO、CSDN、碼農家園、博客園等很多技術文章都沒有很準確的springmvc集成Sentinel的示例,因此整理了本文,主要介紹SpringMvc集成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
二、Sentinel 基本概念
資源
資源是 Sentinel 的關鍵概念。它可以是 Java 應用程式中的任何內容,例如,由應用程式提供的服務,或由應用程式調用的其它應用提供的服務,甚至可以是一段代碼。在接下來的文檔中,我們都會用資源來描述代碼塊。
只要通過 Sentinel API 定義的代碼,就是資源,能夠被 Sentinel 保護起來。大部分情況下,可以使用方法簽名,URL,甚至服務名稱作為資源名來標示資源。
規則
圍繞資源的實時狀態設定的規則,可以包括流量控制規則、熔斷降級規則以及系統保護規則。所有規則可以動態實時調整。
三、springMVC集成Sentinel
這裡用的是spring
<spring.version>5.3.18</spring.version>
<servlet.api.version>2.5</servlet.api.version> <sentinel.version>1.8.6</sentinel.version>
1、springmvc項目引入依賴pom
<!-- 這是sentinel的核心依賴 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-core</artifactId>
<version>${sentinel.version}</version>
</dependency>
<!-- 這是將自己項目和sentinel-dashboard打通的依賴 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-transport-simple-http</artifactId>
<version>${sentinel.version}</version>
</dependency>
<!-- 這是使用sentinel對限流資源進行AOP -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-annotation-aspectj</artifactId>
<version>${sentinel.version}</version>
</dependency>
<!--這是使用sentinel適配Web Servlet的依賴-->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-web-servlet</artifactId>
<version>${sentinel.version}</version>
</dependency>
<!-- 這是使用sentinel熱點參數限流功能依賴 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-parameter-flow-control</artifactId>
<version>${sentinel.version}</version>
</dependency>
2、添加配置文件
在application.properties下創建同級文件sentinel.properties,內容如下
# 集成到sentinel的項目名稱
project.name=spring-sentinel-demo
# 對應的sentinel-dashboard地址
csp.sentinel.dashboard.server=localhost: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 {
@Bean
public SentinelResourceAspect sentinelResourceAspect() {
return new SentinelResourceAspect();
}
}
4、web.xml新增如下過濾器配置
<filter>
<filter-name>SentinelCommonFilter</filter-name>
<filter-class>com.alibaba.csp.sentinel.adapter.servlet.CommonFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SentinelCommonFilter</filter-name>
<url-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")
@ResponseBody
public String apiHello(String id) {
System.out.println("id = " + id);
Date date = new Date();
System.out.println("date = " + date);
return "Hello!";
}
@GetMapping("/doBusiness")
@ResponseBody
public 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.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-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")
@ResponseBody
public String RequestMapping(String id) {
return "RequestMapping!";
}
@GetMapping("/GetMapping")
@ResponseBody
public String GetMapping(String id) {
return "GetMapping...";
}
@PostMapping("/PostMapping")
@ResponseBody
public String PostMapping(String id) {
return "PostMapping...";
}
/*
* 路徑變數(Path Variables):使用花括弧 {} 來標記路徑中的變數,並通過 @PathVariable 註解將其綁定到方法參數上
* */
@GetMapping("/GetMapping/{id}")
@ResponseBody
public String apiFoo(@PathVariable("id") Long id) {
return "Hello " + id;
}
/*
* Ant風格的路徑匹配:
* 使用 ? 表示任意單個字元,
* * 表示任意多個字元(不包含路徑分隔符 /),
* ** 表示任意多個字元(包含路徑分隔符 /)。
* */
@GetMapping("/Ant/*/{id}")
@ResponseBody
public String Ant(@PathVariable("id") Long id) {
return "Ant " + id;
}
/*
* 正則表達式路徑匹配:使用 @RequestMapping 註解的 value 屬性結合正則表達式來定義請求路徑。
* */
@GetMapping(value = "/users/{id:\\d+}")
@ResponseBody
public 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 {
@Override
public 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;
Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();
for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : handlerMethods.entrySet()) {
RequestMappingInfo requestMappingInfo = entry.getKey();
HandlerMethod handlerMethod = entry.getValue();
//匹配url
if (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;
}
//匹配路徑帶參數的url
UrlPathHelper 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;charset=utf-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。
作者:京東健康 馬仁喜
來源:京東雲開發者社區 轉載請註明來源