从ruoyi-gateway中学习sentinel的用法

sentinel中文的含义是哨兵,它是阿里开发的一个限流、降级和熔断的开源框架。作用等同于hystrix,但是sentinel更加强大,功能更加丰富。它的功能包括:

  1. 限流
  2. 降级
  3. 热点参数限流
  4. 系统负载保护
  5. 授权
  6. 熔断
  7. 服务熔断
  8. 系统负载保护
    具体的功能和教程可以参见官网:sentinel官网文档,我们主要简单的看看如何在spring cloud gateway中使用sentinel。

sentinel的使用

1. 引入依赖

首先我们需要引入sentinel的依赖,我们可以在pom.xml中添加如下依赖:

<!-- SpringCloud Alibaba Sentinel -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>

        <!-- SpringCloud Alibaba Sentinel Gateway -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
        </dependency>

        <!-- Sentinel Datasource Nacos -->
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-datasource-nacos</artifactId>
        </dependency>

2. 配置文件

在配置文件中添加如下配置:

spring:
  cloud:
    sentinel:
      # 取消控制台懒加载
      eager: true
      transport:
        # 控制台地址
        dashboard: 127.0.0.1:8718
      # nacos配置持久化
      datasource:
        ds1:
          nacos:
            server-addr: 127.0.0.1:8848
            dataId: sentinel-gateway
            groupId: DEFAULT_GROUP
            data-type: json
            rule-type: flow

我们可以看到在配置文件中,配置了sentinel的控制台地址,以及nacos的配置持久化。
这里我们需要注意的是,sentinel的控制台地址是必须配置的,否则sentinel的控制台将无法访问。
而nacos的配置持久化是可选的,如果不配置,那么sentinel的规则将无法持久化,重启后将会失效。

3. 配置sentinel规则

在若依中,我们主要使用了nacos作为sentinel的规则存储中心,所以我们需要在nacos中添加sentinel的规则。

在nacos中添加规则的方式比较简单, 我们只需要在nacos中添加一个dataId为sentinel-gateway的配置,然后在配置中添加如下内容:

[
  {
    
    
    "resource": "/api/**",
    "limitApp": "default",
    "grade": 1,
    "count": 1,
    "strategy": 0,
    "controlBehavior": 0,
    "clusterMode": false
  }
]

其中规则的具体含义如下:

  • resource:资源名称,可以是网关中的路由名称或者用户自定义的API分组名称。
  • limitApp:流控针对的调用来源,若为 default 则不区分调用来源。否则,若调用来源不是 default,则只有调用来源是 limitApp 的流量才会进行流控。
  • grade:限流阈值类型,QPS 或线程数。具体的值为 0 或 1,分别对应 QPS 和线程数。
  • count:限流阈值。
  • strategy:调用关系限流策略,目前只支持直接、关联和链路三种模式。具体的值为 0、1、2,分别对应直接、关联和链路。
  • controlBehavior:流控效果(直接拒绝、Warm Up、匀速排队)。具体的值为 0、1、2,分别对应直接拒绝、Warm Up、匀速排队。
  • clusterMode:是否为集群模式。

4. 启动Dashboard

  1. 下载最新的dashboard, 去github下载合适的dashboard版本 https://github.com/alibaba/Sentinel/releases
  2. 执行下面命令启动dashboard
java -Dserver.port=8718 -Dcsp.sentinel.dashboard.server=localhost:8718 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard-1.8.0.jar
  1. 访问dashboard http://localhost:8718,默认的账户和密码都是sentinel

猜你喜欢

转载自blog.csdn.net/aofengdaxia/article/details/129294025
今日推荐