SpringCloud 整合 Sentinel

Sentinel 是阿里开源的分布式流量哨兵,具有限流、熔断降级、服务监控等功能。

下面介绍在 SpringCloud中的具体使用方式。

目录

1. 下载并启动 Sentinel 控制台服务

2. 引入起步依赖

3. 配置

4. 代码

5. 使用

6. 验证结果


1. 下载并启动 Sentinel 控制台服务

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

2. 引入起步依赖

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

3. 配置


spring:
  profiles:
    active: dev
  application:
    name: springboot-hello
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8849
      config:
        server-addr: 127.0.0.1:8849
        # 扩展名必须要严格一致:springboot-hello-dev.yml,
        # 如果配置成 .yaml, 则 springboot-hello-dev.yaml
        file-extension: yml
    sentinel:
      transport:
        dashboard: localhost:8070

server:
  port: 9000

4. 代码

    /**
     * 被调用方的 sentinel fallback 优先调用方的 feignClient 的 fallback
     *
     * 1. fallback 是异常降级,只要出现业务异常后,会走 fallback 指定的方法;
     * 2. 达到相应的阈值时,才会触发熔断和限流,都会抛出 BlockException 由 blockHandler 方法处理;
     *
     */
    @SentinelResource(value = "sayHello", fallback = "sayDefaultHello",blockHandler = "blockWarn")
    @RequestMapping("/hello")
    @RequestMapping("/hello")
    public String hello(){
        int b = 1/0;
        return String.format("Hello 【%s】", username);
    }

    // 异常降级,只针对业务异常!
    public String sayDefaultHello(){
        return String.format("Hello World!");
    }

    // 熔断降级、流控 都会触发 BlockException
    public  String blockWarn(BlockException e) {
        if (e instanceof FlowException) {
            return "访问太频繁,稍后重试!";
        }

        if (e instanceof DegradeException) {
            return "服务已自动断开,稍后重试!";
        }

        return "稍后重试";
    }

5. 使用

在 dashboard 配置流控规则和熔断规则:

6. 验证结果

1. 首次访问,触发 fallback 

2. 连续频繁刷新,触发限流

 3. 访问多次,达到熔断策略,触发熔断

如果觉得还不错的话,关注、分享、在看(关注不失联~), 原创不易,且看且珍惜~

posted on 2021-10-12 11:35  XuHe1  阅读(108)  评论(0编辑  收藏  举报