zuul集成Sentinel完成對path映射的限流
前面我們講過了對單體應用的Sentinel限流,以及使用zookeeper對規則的持久化。通過前面的工作,我們可以完成單個實例的細粒度的限流、熔斷操作。
譬如有一個服務User,在分布式環境下,開啟了多個實例,那么每個實例都可以獲得如每秒限制10個登錄的限流功能。但是有些場景下,我們想要另外一種限流方式,譬如在網關zuul層,想限制對User服務的限流,而不去關心具體它有多少個實例。這時,就需要用到網關限流了。
Sentinel 1.6.0 引入了 Sentinel API Gateway Adapter Common 模塊,包含網關限流的規則和自定義 API 的實體和管理邏輯:
GatewayFlowRule
:網關限流規則,針對 API Gateway 的場景定制的限流規則,可以針對不同 route 或自定義的 API 分組進行限流,支持針對請求中的參數、Header、來源 IP 等進行定制化的限流。
ApiDefinition
:用戶自定義的 API 定義分組,可以看做是一些 URL 匹配的組合。比如我們可以定義一個 API 叫 my_api,請求 path 模式為 /foo/** 和 /baz/** 的都歸到 my_api 這個 API 分組下面。
限流的時候可以針對這個自定義的 API 分組維度進行限流。
注意這個版本,1.6.0以后才有的。
我們直接上代碼,進入實戰。新建一個SpringCloud項目,選中zuul。并在啟動類上加上@EnableZuulProxy注解,代表這是一個zuul網關項目。
pom.xml如下:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.6.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>sentinelzuul</artifactId> <version>0.0.1-SNAPSHOT</version> <name>sentinelzuul</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> <spring-cloud.version>Greenwich.SR1</spring-cloud.version> <sentinel.version>1.6.1</sentinel.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-zuul</artifactId> </dependency> <!--<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> </dependency> <dependency> <groupId>com.alibaba.csp</groupId> <artifactId>sentinel-datasource-zookeeper</artifactId> </dependency>--> <dependency> <groupId>com.alibaba.csp</groupId> <artifactId>sentinel-zuul-adapter</artifactId> <version>${sentinel.version}</version> </dependency> <dependency> <groupId>com.alibaba.csp</groupId> <artifactId>sentinel-core</artifactId> <version>${sentinel.version}</version> </dependency> <dependency> <groupId>com.alibaba.csp</groupId> <artifactId>sentinel-parameter-flow-control</artifactId> <version>${sentinel.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-alibaba-dependencies</artifactId> <version>0.2.2.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
官方文檔上寫,只需要引入sentinel-zuul-adapter依賴,實測后發現,只引入這個的話,所依賴的Sentinel-core是1.5.2版本,會導致啟動失敗。所以我手工加入了其他幾個依賴。
yml文件如下:
server: port: 9999 zuul: routes: one: path: /baoban/** url: http://localhost:8888/baoban/ spring: application: name: sentinelzuul
這里配了一個簡單的routes映射。那是另外一個本地服務。
使用zuul的限流很簡單,2個類即可
ZuulConfig.java
import com.alibaba.csp.sentinel.adapter.gateway.zuul.filters.SentinelZuulErrorFilter; import com.alibaba.csp.sentinel.adapter.gateway.zuul.filters.SentinelZuulPostFilter; import com.alibaba.csp.sentinel.adapter.gateway.zuul.filters.SentinelZuulPreFilter; import com.netflix.zuul.ZuulFilter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @author wuweifeng wrote on 2019/7/3. */ @Configuration public class ZuulConfig { @Bean public ZuulFilter sentinelZuulPreFilter() { return new SentinelZuulPreFilter(10000); } @Bean public ZuulFilter sentinelZuulPostFilter() { return new SentinelZuulPostFilter(1000); } @Bean public ZuulFilter sentinelZuulErrorFilter() { return new SentinelZuulErrorFilter(-1); } }
package com.example.sentinelzuul.config; import com.alibaba.csp.sentinel.adapter.gateway.common.SentinelGatewayConstants; import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition; import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPathPredicateItem; import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPredicateItem; import com.alibaba.csp.sentinel.adapter.gateway.common.api.GatewayApiDefinitionManager; import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule; import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayParamFlowItem; import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager; import com.alibaba.csp.sentinel.slots.block.RuleConstant; import org.springframework.context.annotation.Configuration; import javax.annotation.PostConstruct; import java.util.HashSet; import java.util.Set; /** * @author wuweifeng wrote on 2019/7/3. */ @Configuration public class GatewayRuleConfig { private static final int URL_MATCH_STRATEGY_EXACT = 0; private static final int URL_MATCH_STRATEGY_PREFIX = 1; private static final int URL_MATCH_STRATEGY_REGEX = 2; @PostConstruct public void doInit() { // Prepare some gateway rules and API definitions (only for demo). // It"s recommended to leverage dynamic data source or the Sentinel dashboard to push the rules. initCustomizedApis(); initGatewayRules(); } private void initCustomizedApis() { Set<ApiDefinition> definitions = new HashSet<>(); ApiDefinition api1 = new ApiDefinition("baobao_api") .setPredicateItems(new HashSet<ApiPredicateItem>() {{ //add(new ApiPathPredicateItem().setPattern("/ahas")); add(new ApiPathPredicateItem().setPattern("/baoban/**") .setMatchStrategy(URL_MATCH_STRATEGY_PREFIX)); }}); //ApiDefinition api2 = new ApiDefinition("another_customized_api") // .setPredicateItems(new HashSet<ApiPredicateItem>() {{ // add(new ApiPathPredicateItem().setPattern("/**") // .setMatchStrategy(URL_MATCH_STRATEGY_PREFIX)); // }}); definitions.add(api1); //definitions.add(api2); GatewayApiDefinitionManager.loadApiDefinitions(definitions); } private void initGatewayRules() { Set<GatewayFlowRule> rules = new HashSet<>(); rules.add(new GatewayFlowRule("baobao_api") .setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME) .setCount(1) .setIntervalSec(1) ); rules.add(new GatewayFlowRule("aliyun-product-route") .setCount(2) .setIntervalSec(2) //應對突發請求時額外允許的請求數目。 .setBurst(2) .setParamItem(new GatewayParamFlowItem() .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_CLIENT_IP) ) ); rules.add(new GatewayFlowRule("another-route-httpbin") .setCount(10) //統計時間窗口,單位是秒,默認是 1 秒。 .setIntervalSec(1) //流量整形的控制效果,同限流規則的 controlBehavior 字段,目前支持快速失敗和勻速排隊兩種模式,默認是快速失敗。 .setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER) //勻速排隊模式下的最長排隊時間,單位是毫秒,僅在勻速排隊模式下生效。 .setMaxQueueingTimeoutMs(600) //參數限流配置 .setParamItem(new GatewayParamFlowItem() .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER) .setFieldName("X-Sentinel-Flag") ) ); rules.add(new GatewayFlowRule("another-route-httpbin") .setCount(1) .setIntervalSec(1) .setParamItem(new GatewayParamFlowItem() .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM) .setFieldName("pa") ) ); rules.add(new GatewayFlowRule("some_customized_api") .setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME) .setCount(5) .setIntervalSec(1) .setParamItem(new GatewayParamFlowItem() .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM) .setFieldName("pn") ) ); GatewayRuleManager.loadRules(rules); //監聽zookeeper,使用zookeeper的規則 //ReadableDataSource<String, Set<GatewayFlowRule>> flowRuleDataSource = new ZookeeperDataSource<>(null, null, // source -> JSON.parseObject(source, new TypeReference<Set<GatewayFlowRule>>() { // })); //GatewayRuleManager.register2Property(flowRuleDataSource.getProperty()); } }
主要做的有2件事
1是配置一下APIDefinition,也就是給自己的映射規則起個名字。
2是配置Rule,和之前的配置rule差不多。創建一個rule的集合,設置rule規則,具體規則各字段在上面截圖中有解釋。
這里我配了一個簡單的一秒1個QPS的規則。最后用GatewayRuleManager去loadRules即可。
之后測試一下就發現規則已生效。頻繁訪問被限流的服務時,會報下面的異常。
如果你想自定義這個熔斷的返回值的話,可以加個類實現ZuulBlockFallbackProvider:
import com.alibaba.csp.sentinel.adapter.gateway.zuul.fallback.BlockResponse; import com.alibaba.csp.sentinel.adapter.gateway.zuul.fallback.DefaultBlockFallbackProvider; import com.alibaba.csp.sentinel.adapter.gateway.zuul.fallback.ZuulBlockFallbackProvider; import com.alibaba.csp.sentinel.log.RecordLog; import com.alibaba.csp.sentinel.slots.block.BlockException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author wuweifeng wrote on 2019/7/3. */ public class MyBlockFallbackProvider implements ZuulBlockFallbackProvider { private Logger logger = LoggerFactory.getLogger(DefaultBlockFallbackProvider.class); // you can define route as service level @Override public String getRoute() { return "baobao_api"; } @Override public BlockResponse fallbackResponse(String route, Throwable cause) { RecordLog.info(String.format("[Sentinel DefaultBlockFallbackProvider] Run fallback route: %s", route)); if (cause instanceof BlockException) { return new BlockResponse(429, "the route is blocked", route); } else { return new BlockResponse(500, "System Error", route); } } }
getRoute方法返回的就是上面定義的resouceName。然后注冊一下就好了。
當然這也是基于內存的規則,不能動態改變,在實際生產中,如果需要動態改變規則的話,還是需要去用zookeeper之類的。
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://tianyalei.blog.csdn.net/article/details/94577775