Spring Cloud Alibaba Sentinel 网关限流与Spring Cloud Gateway整合

网关限流

Sentinel 支持对 Spring Cloud Gateway、Zuul 等主流的 API Gateway 进行限流。

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 分组维度进行限流。

Gateway 中配置的,route ID(如 product_route)和 API name(如 some_customized_api)会被自动标识为 Sentinel 的资源。其实现逻辑在 SentinelGatewayFilter 中

添加依赖

Spring Cloud Gateway 应用下添加如下依赖

<!-- 添加Sentinel依赖 -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!-- 添加Sentinel DataSource Nacos依赖 -->
<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-datasource-nacos</artifactId>
    <version>1.8.6</version>
</dependency>
<!-- 添加 Sentinel Gateway 依赖 -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>

配置

@Configuration
public class GatewayConfiguration {

    private final List<ViewResolver> viewResolvers;
    private final ServerCodecConfigurer serverCodecConfigurer;

    public GatewayConfiguration(ObjectProvider<List<ViewResolver>> viewResolversProvider,
                                ServerCodecConfigurer serverCodecConfigurer) {
        this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
        this.serverCodecConfigurer = serverCodecConfigurer;
    }

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
        // Register the block exception handler for Spring Cloud Gateway.
        return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
    }

    @Bean
    @Order(-1)
    public GlobalFilter sentinelGatewayFilter() {
        return new SentinelGatewayFilter();
    }
}

我们的示例是Spring Cloud 应用,而且引入了 spring-cloud-alibaba-sentinel-gateway,其 SentinelSCGAutoConfiguration 类中定义了上面的内容。所以我们的示例中不用手动定义。

配置 spring.cloud.sentinel.filter.enabled 配置项置为 false(若在网关流控控制台上看到了 URL 资源,就是此配置项没有置为 false)。Sentinel 网关流控默认的粒度是 route 维度以及自定义 API 分组维度,默认不支持 URL 粒度。

网关限流规则 GatewayFlowRule

  • resource:资源名称,可以是网关中的 route 名称或者用户自定义的 API 分组名称。
  • resourceMode:规则是针对 API Gateway 的 route(RESOURCE_MODE_ROUTE_ID)还是用户在 Sentinel 中定义的 API 分组(RESOURCE_MODE_CUSTOM_API_NAME),默认是 route。
  • grade:限流指标维度,同限流规则的 grade 字段。
  • count:限流阈值
  • intervalSec:统计时间窗口,单位是秒,默认是 1 秒。
  • controlBehavior:流量整形的控制效果,同限流规则的 controlBehavior 字段,目前支持快速失败和匀速排队两种模式,默认是快速失败。
  • burst:应对突发请求时额外允许的请求数目。
  • maxQueueingTimeoutMs:匀速排队模式下的最长排队时间,单位是毫秒,仅在匀速排队模式下生效。
  • paramItem:参数限流配置。若不提供,则代表不针对参数进行限流,该网关规则将会被转换成普通流控规则;否则会转换成热点规则。其中的字段:
    • parseStrategy:从请求中提取参数的策略,目前支持提取来源 IP(PARAM_PARSE_STRATEGY_CLIENT_IP)、Host(PARAM_PARSE_STRATEGY_HOST)、任意 Header(PARAM_PARSE_STRATEGY_HEADER)和任意 URL 参数(PARAM_PARSE_STRATEGY_URL_PARAM)四种模式。
    • fieldName:若提取策略选择 Header 模式或 URL 参数模式,则需要指定对应的 header 名称或 URL 参数名称。
    • pattern:参数值的匹配模式,只有匹配该模式的请求属性值会纳入统计和流控;若为空则统计该请求属性的所有值。(1.6.2 版本开始支持)
    • matchStrategy:参数值的匹配策略,目前支持精确匹配(PARAM_MATCH_STRATEGY_EXACT)、子串匹配(PARAM_MATCH_STRATEGY_CONTAINS)和正则匹配(PARAM_MATCH_STRATEGY_REGEX)。(1.6.2 版本开始支持)

网关限流的动态数据源配置

import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition;
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.GatewayRuleManager;
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource;
import com.alibaba.csp.sentinel.init.InitFunc;
import com.alibaba.csp.sentinel.init.InitOrder;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.fasterxml.jackson.core.type.TypeReference;

import java.util.Properties;
import java.util.Set;

/**
 * Gateway 流控
 */
@InitOrder(1) // 用于定义执行顺序
public class MyGatewayInitFunc implements InitFunc {

    /**
     * Nacos 地址
     */
    public static final String NACOS_ADDRS = "localhost:8848";

    /**
     * 对应 Nacos 的命名空间 ID
     *
     *  fd315d16-12ef-4d67-b8e2-8dfe2e6667b5
     *  855e91a2-60e7-48c3-aa3f-27aa2f8a0f73
     */
    public static final String NACOS_SENTINEL_NAMESPACE = "fd315d16-12ef-4d67-b8e2-8dfe2e6667b5";

    /**
     * Nacos group id
     */
    public static final String NACOS_SENTINEL_GROUPID = "Sentinel_Demo_Group";

    /**
     * 网关限流规则 dataID
     */
    public static final String NACOS_SENTINEL_GATEWAY_RULES_DATAID = "Gateway-Flow-Rule";

    /**
     * 网关API组合限流 dataID
     */
    public static final String NACOS_SENTINEL_GATEWAY_API_DATAID = "Gateway-API-Rule";


    @Override
    public void init() throws Exception {
        // Nacos 配置
        Properties nacosPro = new Properties();
        nacosPro.put(PropertyKeyConst.SERVER_ADDR,NACOS_ADDRS);
        nacosPro.put(PropertyKeyConst.NAMESPACE,NACOS_SENTINEL_NAMESPACE);

        // 根据 Gateway router 限流 (注意:GatewayFlowRule 是 Set 列表,不是 List)
        ReadableDataSource<String, Set<GatewayFlowRule>> ds = new NacosDataSource<>(nacosPro, NACOS_SENTINEL_GROUPID, NACOS_SENTINEL_GATEWAY_RULES_DATAID,
                source -> JsonUtil.toGenericBean(source, new TypeReference<Set<GatewayFlowRule>>(){}));
        GatewayRuleManager.register2Property(ds.getProperty());

        // 根据 API 限流 ApiDefinition 类非常简单,我们就不做详细分析了
        ReadableDataSource<String, Set<ApiDefinition>> dsApiDefinition = new NacosDataSource<>(nacosPro, NACOS_SENTINEL_GROUPID, NACOS_SENTINEL_GATEWAY_API_DATAID,
                source -> JsonUtil.toGenericBean(source, new TypeReference<Set<ApiDefinition>>(){}));
        GatewayApiDefinitionManager.register2Property(dsApiDefinition.getProperty());

    }
}

注:使用Spring Cloud 配置方式动态规则配置,网关流控规则数据源类型是 gw-flow,API配置数据源类型是 gw-api-group。

网关流控后的处理

默认情况下,被流控的网关请求返回如下内容

{
    "code": 429,
    "message": "Blocked by Sentinel: ParamFlowException"
}

配置自定义的流控返回结果

配置 SentinelGatewayProperties 中的 FallbackProperties


	/**
	 * 类型 `redirect` 或者 `response`.
	 */
	private String mode;

	/**
	 * 如果类型为 `redirect` 则此值必填
	 */
	private String redirect;

	/**
	 * 类型为 `response` 时,返回的响应结果.
	 * publisher/producer 
	 */
	private String responseBody;

	/**
	 * 类型为 `response` 时,返回的状态码,默认为 429 Too Many Requests
	 */
	private Integer responseStatus = HttpStatus.TOO_MANY_REQUESTS.value();

	/**
	 * 类型为 `response` 时,响应的content-type,默认为json.
	 */
	private String contentType = MediaType.APPLICATION_JSON.toString();

其自动配置的定义代码,在 SentinelSCGAutoConfiguration 类中。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值