SpringMvc整合開源流量監控、限流、熔斷降級、負載保護元件Sentinel

2023-11-30 12:05:54

前言:作者查閱了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.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

作者:京東健康 馬仁喜

來源:京東雲開發者社群 轉載請註明來源