最近在搞gateway模块集成Sentinel,一头包,看了很多文章,但归根结底是没搞清楚为什么。

下面这个组件大坑,不要轻易用!!

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

先说结论:严格按照下面的进行配置,gateway中集成sentinel依赖,user中不需要集成,持久化的代码在user的nacos中做就可以了就这么简单

项目gateway中的pom依赖如下:

<dependencies>


    <!--gateway组件-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>

    <!--nacos服务发现和注册组件-->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
    </dependency>



  <!--sentinel限流熔断组件-->

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


</dependencies>

application.yml配置如下

server:
  port: 8880

spring:
  datasource:
    #    type: com.zaxxer.hikari.HikariDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql:*******
    username: 
    password: 
    hikari:
      ## 最小空闲连接数量
      minimum-idle: 5
      ## 连接池最大连接数,默认是10
      maximum-pool-size: 10
      ## 默认自动提交
      auto-commit: true
      ## 空闲连接存活最大时间,默认600000(10分钟)
      idle-timeout: 180000
      ## 此属性控制池中连接的最长生命周期,值0表示无限生命周期,默认1800000即30分钟
      max-lifetime: 1800000
      ## 连接池名字
      pool-name: CommnuityUserHikariCP
      ## 数据库连接超时时间,默认30秒,即30000
      connection-timeout: 30000
      connection-test-query: SELECT 1
  cloud:
    # 网关gateway配置
    gateway:
      discovery:
        locator:
          enabled: true
      # 路由配置
      routes:
        - id: commnuity-user  # 路由的唯一标识,
          uri: lb://commnuity-user  # 路由到user;路由目的地,支持lb(服务名)和http两种
          # 断言规则,用于路由规则的匹配;判断是否符合请求,符合则转发到路由目的地
          predicates:
            # 因为是字符串所以可以这样写,自动映射;  -path中是服务的前缀
            # http://localhost:8880/user/getMsg/saveStockInfo 路由到↓
            # http://localhost:8881/user/getMsg/saveStockInfo
            - Path=/user/**
    sentinel:
      # 取消控制台懒加载
      eager: true
      transport:
        # 控制台地址
        dashboard: 192.168.1.6:8851
        port: 8720    #默认8719可更改一下,可能端口被占用,直接+1直至显示出board
        client-ip: 192.168.1.6      #集成sentinel所在的服务ip,监控的是所有来gateway机器的请求。
      filter:
        enabled: true
      # 配置默认fallback,也可以编码自定义fallback
      scg.fallback:
          mode: response
          response-status: 429
          response-body: '{"code":429,"message":"被限流了!"}'
      scg:
        order: -100


user用户微服务的依如下:

 <dependencies>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>


        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-bootstrap</artifactId>
        </dependency>


    </dependencies>

user的application.yml如下

server:
  #端口号
  port: 8881
  servlet:
    context-path: /user

spring:
  datasource:
    #    type: com.zaxxer.hikari.HikariDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql:xxx
    username: xx
    password: xx
    hikari:
      ## 最小空闲连接数量
      minimum-idle: 5
      ## 连接池最大连接数,默认是10
      maximum-pool-size: 10
      ## 默认自动提交
      auto-commit: true
      ## 空闲连接存活最大时间,默认600000(10分钟)
      idle-timeout: 180000
      ## 此属性控制池中连接的最长生命周期,值0表示无限生命周期,默认1800000即30分钟
      max-lifetime: 1800000
      ## 连接池名字
      pool-name: CommnuityUserHikariCP
      ## 数据库连接超时时间,默认30秒,即30000
      connection-timeout: 30000
      connection-test-query: SELECT 1
  cloud:
    sentinel:
      transport:
        dashboard: 192.168.1.6:8851
        port: 8720    #默认8719可更改一下,可能端口被占用,直接+1直至显示出board
        client-ip: 192.168.1.6      #集成sentinel所在的服务ip,监控的是所有来gateway机器的请求。
      scg.fallback:
          mode: response
          response-status: 200
          response-body: '{"code":429,"message":"被限流了!"}'
      eager: true
      datasource:
        ds1:
          nacos: #限流持久配置
            server-addr: 192.168.1.26:8848 #nacos的访问地址,,根据上面准备工作中启动的实例配置
            username: nacos
            password: nacos
            dataId: commnuity-user            #nacos中存储规则的dataId
            groupId: DEFAULT_GROUP #nacos中存储规则的groupId
            namespace: 2f0a6eaa-02ee-4bcf-956c-283a4177d4c2 #Nacos 命名空间的ID
            data-type: json #配置文件类型
            rule-type: flow #类型来自RuleType类 - 流控规则

mybatis:
  mapper-locations: classpath:mapper/*.xml

management:
  endpoint:
    sentinel:
      enabled: true

nacos配置

[
    {
         "resource": "user-testFlow",
         "limitApp": "default",
         "grade":   1,
         "count":   1,
         "strategy": 0,
         "controlBehavior": 0,
         "clusterMode": false    
    }
]

user的测试类如下

    /**
     * 测试流控规则
     */
    @PostMapping("/testFlow")
    @SentinelResource(value = "user-testFlow",
            blockHandlerClass = UserBlockHandler.class, //对应异常类
            blockHandler = "handleException",  //只负责sentinel控制台配置违规
            fallback = "handleError",   //只负责业务异常
            fallbackClass = UserBlockHandler.class)
    public String testFlow() {

        return JSON.toJSONString("限流测试");
    }

GitHub 加速计划 / sentine / Sentinel
49
7
下载
alibaba/Sentinel: Sentinel 是阿里巴巴开源的一款面向分布式服务架构的流量控制、熔断降级组件,提供实时监控、限流、降级和系统保护功能,适用于微服务治理场景。
最近提交(Master分支:4 个月前 )
222670e6 * fix: Endpoint#toString host formatting; add Endpoint unit test * test: remove empty EndpointTest.java (fix accidental PR changes) --------- Signed-off-by: 赖尧 <yujitang_2006@qq.com> 1 个月前
e7a9c560 * chore: remove node_modules from git & add to .gitignore * fix(docs): normalize README table style (MD060) across adapters and cluster modules * docs: fix compact table style in parameter flow README * docs: fix markdownlint MD009 and MD060 in README files * docs: fix table format in parameter-flow-control README (MD060/MD009) * docs: fix table format in spring-webmvc README files (MD060/MD009) * fix: restore UTF-8 encoding and fix markdownlint errors * fix: wrap remaining bare URLs with angle brackets (MD034) * fix: remove trailing spaces from table rows (MD009) --------- Signed-off-by: 赖尧 <yujitang_2006@qq.com> 1 个月前
Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐