Sentinel 快速上手

292 阅读5分钟

Sentinel 是阿里巴巴开源的一款轻量级的流量控制、熔断降级 Java 库,它可用于防护应用流量峰值、系统负载过高等场景,保障了微服务的稳定性和高可用性。

简介: introduction | Sentinel

image.png

快速上手

快速开始 | Spring Cloud Alibaba
1、引入依赖

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

简单示例

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(ServiceApplication.class, args);
    }
}
@RestController
public class TestController {

    @GetMapping(value = "/hello")
    @SentinelResource("hello")
    public String hello() {
        return "Hello Sentinel";
    }
}

结合 OpenFeign 使用

进阶指南 | Spring Cloud Alibaba

结合 Spring Cloud Alibaba 使用

快速开始 | Spring Cloud Alibaba

在 Spring Cloud Alibaba 中结合 Nacos 使用

进阶指南-动态数据源配置 | Spring Cloud Alibaba
官方示例:

spring.cloud.sentinel.datasource.ds1.file.file=classpath: degraderule.json
spring.cloud.sentinel.datasource.ds1.file.rule-type=flow

#spring.cloud.sentinel.datasource.ds1.file.file=classpath: flowrule.json
#spring.cloud.sentinel.datasource.ds1.file.data-type=custom
#spring.cloud.sentinel.datasource.ds1.file.converter-class=org.springframework.cloud.alibaba.cloud.examples.JsonFlowRuleListConverter
#spring.cloud.sentinel.datasource.ds1.file.rule-type=flow

spring.cloud.sentinel.datasource.ds2.nacos.server-addr=127.0.0.1:8848
spring.cloud.sentinel.datasource.ds2.nacos.data-id=sentinel
spring.cloud.sentinel.datasource.ds2.nacos.group-id=DEFAULT_GROUP
spring.cloud.sentinel.datasource.ds2.nacos.data-type=json
spring.cloud.sentinel.datasource.ds2.nacos.rule-type=degrade

spring.cloud.sentinel.datasource.ds3.zk.path = /Sentinel-Demo/SYSTEM-CODE-DEMO-FLOW
spring.cloud.sentinel.datasource.ds3.zk.server-addr = localhost:2181
spring.cloud.sentinel.datasource.ds3.zk.rule-type=authority

spring.cloud.sentinel.datasource.ds4.apollo.namespace-name = application
spring.cloud.sentinel.datasource.ds4.apollo.flow-rules-key = sentinel
spring.cloud.sentinel.datasource.ds4.apollo.default-flow-rule-value = test
spring.cloud.sentinel.datasource.ds4.apollo.rule-type=param-flow

这种配置方式参考了 Spring Cloud Stream Binder 的配置,内部使用了 TreeMap 进行存储,comparator 为 String. CASE_INSENSITIVE_ORDER 。
NOTE: d 1, ds 2, ds 3, ds 4 是 ReadableDataSource 的名字,可随意编写。后面的 file ,zk ,nacos , apollo 就是对应具体的数据源。它们后面的配置就是这些具体数据源各自的配置。
每种数据源都有两个共同的配置项: data-type、 converter-class 以及 rule-type。
Data-type 配置项表示 Converter 类型,Spring Cloud Alibaba Sentinel 默认提供两种内置的值,分别是 json 和 xml (不填默认是 json)。如果不想使用内置的 json 或 xml 这两种 Converter,可以填写 custom 表示自定义 Converter,然后再配置 converter-class 配置项,该配置项需要写类的全路径名 (比如 spring. Cloud. Sentinel. Datasource. Ds 1. File. Converter-class=org. Springframework. Cloud. Alibaba. Cloud. Examples. JsonFlowRuleListConverter)。
Rule-type 配置表示该数据源中的规则属于哪种类型的规则 (flow,degrade,authority, system, param-flow, gw-flow, gw-api-group)。
NOTE: 当某个数据源规则信息加载失败的情况下,不会影响应用的启动,会在日志中打印出错误信息。
NOTE: 默认情况下,xml 格式是不支持的。需要添加 jackson-dataformat-xml 依赖后才会自动生效。

在 Spring Cloud Alibaba 中结合 Spring Cloud Gateway 使用

官网文档: 网关流量控制 | Sentinel
Spring Cloud Alibaba Sentinel 网关限流与Spring Cloud Gateway整合_springcloudalibaba gateway限流 与sentinel限流-CSDN博客

配置网关路由限流

1、添加相关依赖

<dependency>  
    <groupId>com.alibaba.cloud</groupId>  
    <artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>  
</dependency>

<dependency>  
    <groupId>com.alibaba.cloud</groupId>  
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>  
    <!--            <version>2022.0.0.0</version>-->  
</dependency>

<dependency>  
    <groupId>com.alibaba.csp</groupId>  
    <artifactId>sentinel-datasource-nacos</artifactId>  
    <version>1.8.7</version>  
</dependency>

2、在 nacos 中创建规则文件 针对服务进行全局配置


[
  {
    "resourceMode": 0,
    "resource": "service-user",
    "limitApp": "default",
    "grade": 1,
    "count": 20
  },
  {
    "resourceMode": 0,
    "resource": "service-order",
    "limitApp": "default",
    "grade": 1,
    "count": 1
  },
  {
    "resourceMode": 0,
    "resource": "service-commodity",
    "limitApp": "default",
    "grade": 1,
    "count": 1
  }
]

具体的属性,见 api-gateway-flow-control | Sentinelbasic-api-resource-rule | Sentinel
3、在配置文件中添加配置


spring:
  cloud:
    sentinel:
	  filter:
	    enabled: false
      transport:
	    # 这里的 spring.cloud.sentinel.transport.port 端口配置会在应用对应的机器上启动一个 Http Server,该 Server 会与 Sentinel 控制台做交互。比如 Sentinel 控制台添加了 1 个限流规则,会把规则数据 push 给这个 Http Server 接收,Http Server 再将规则注册到 Sentinel 中。
        port: 8719
        dashboard: localhost:8080
      datasource:
        ds1:
          nacos:
            server-addr: localhost:8848
            dataId: sentinel-gateway.json
            namespace: 7b7f3138-dc0e-4ec9-af6c-bc2ffa09a3c0
            groupId: DEFAULT_GROUP
            data-type: json
            #  规则类型,flow 限流规则,degrade 降级规则,system  系统规则,authority 授权规则,param-flow 参数规则
            rule-type: gw-flow
      scg:
        fallback:
          # 响应模式有 redirect 和 response 两种
          mode: response
          response-status: 200
          response-body: '{"code": 429, "message": "哥们,你来的太快了..."}'
          # redirect: https://google.com
    

注意

  • Sentinel 网关流控默认的粒度是 route 维度以及自定义 API 分组维度,默认不支持 URL 粒度。若通过 Spring Cloud Alibaba 接入,请将 spring.cloud.sentinel.filter.enabled 配置项置为 false(若在网关流控控制台上看到了 URL 资源,就是此配置项没有置为 false)。
  • 若使用 Spring Cloud Alibaba Sentinel 数据源模块,需要注意网关流控规则数据源类型是 gw-flow,若将网关流控规则数据源指定为 flow 则不生效。

同时使用 API 分组,自定义部分特殊 url 限流


package pers.yefeng.gateway.config;  
  
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 lombok.extern.slf4j.Slf4j;  
import org.springframework.boot.CommandLineRunner;  
import org.springframework.stereotype.Component;  
  
import java.util.HashSet;  
import java.util.Set;  
  
/**  
 * 项目启动之后运行  
 */  
@Component  
@Slf4j  
public class CommandLineRunnerImpl implements CommandLineRunner {  
    @Override  
    public void run(String... args) throws Exception {  
        initCustomizedApis();  
    }  
  
  
    /**  
     * 自定义API分组  
     */  
    private static void initCustomizedApis() {  
  
        log.info("initCustomizedApis");  
        // 自定义API分组  
        // 可以将这些配置放入配置文件中  
        Set<ApiDefinition> definitions = new HashSet<>();  
        ApiDefinition api1 = new ApiDefinition("customized_api_user")  
                .setPredicateItems(new HashSet<ApiPredicateItem>() {{  
                    add(new ApiPathPredicateItem().setPattern("/user/userInfo/add"));  
//                    add(new ApiPathPredicateItem().setPattern("/product/foo/**").setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_PREFIX));  
                }});  
        ApiDefinition api2 = new ApiDefinition("customized_api_order")  
                .setPredicateItems(new HashSet<ApiPredicateItem>() {{  
                    add(new ApiPathPredicateItem().setPattern("/order/orderInfo/list"));  
                }});  
        definitions.add(api1);  
        definitions.add(api2);  
        GatewayApiDefinitionManager.loadApiDefinitions(definitions);  
    }  
}

修改 sentinel 的配置文件如下,添加自定义 API 组的限流配置。



[
	// 之前的的配置
    {
    "resourceMode": 1,
    "resource": "customized_api_user",
    "limitApp": "default",
    "grade": 1,
    "count": 2
  }
]

当同一个资源对应多个限流规则时,只要有一个规则不通过,则会被限流。

控制台

进阶指南 | Spring Cloud Alibaba 1、下载控制台:Releases · alibaba/Sentinel 2、启动控制台

java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard.jar

3、项目接入控制台 在应用的配置文件中,增加如下控制台配置信息:

spring:
  cloud:
    sentinel:
      transport:
        port: 8719
        dashboard: localhost:8080

这里的 spring. Cloud. Sentinel. Transport. Port 端口配置会在应用对应的机器上启动一个 Http Server,该 Server 会与 Sentinel 控制台做交互。比如 Sentinel 控制台添加了 1 个限流规则,会把规则数据 push 给这个 Http Server 接收,Http Server 再将规则注册到 Sentinel 中。

4、进入控制台:http://localhost:8080/#/login 账号与密码都为 sentinel