Spring Cloud Alibaba Sentinel实现熔断与限流

一、简介

官网
  随着微服务的流行,服务和服务之间的稳定性变得越来越重要。Sentinel 是面向分布式服务架构的流量控制组件,主要以流量为切入点,从限流、流量整形、熔断降级、系统负载保护、热点防护等多个维度来帮助开发者保障微服务的稳定性。
是一个轻量级的流量控制、熔断降级Java库。(类似Hystrix)

1.1 Sentinel主要特性:

在这里插入图片描述

1.2 解决微服务中的问题:

  • 服务雪崩
  • 服务降级
  • 服务熔断
  • 服务限流

1.3 sentinel组件由2部分组成

  • 核心库(Java 客户端):不依赖任何框架/库,能够运行于所有 Java 运行时环境,同时对 Dubbo / Spring Cloud 等框架也有较好的支持。
  • 控制台(Dashboard):基于 Spring Boot 开发,打包后可以直接运行,不需要额外的 Tomcat 等应用容器。

二、安装Sentinel控制台

2.1 下载

https://github.com/alibaba/Sentinel/releases

2.2 运行

由于可以直接运行,不依赖Tomcat
故只要保证:

  • java8环境OK
  • 8080端口不能被占用

然后直接执行命令即可:

java -jar sentinel-dashboard-1.7.0.jar 

2.3 测试

访问sentinel管理界面

http://localhost:8080

登录账号密码均为sentinel

三、初始化演示工程

3.1 启动Nacos8848

3.2 新建测试Module

3.2.1 pom
<dependencies>
        <dependency>
            <groupId>com.cn.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>${project.version}</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <!--后续做持久化操作用到-->
        <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>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>4.6.3</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>
3.2.2 配置yml
server:
  port: 8401

spring:
  application:
    name: cloudalibaba-sentinel-service
  cloud:
    nacos:
      discovery:
        #nacos服务注册中心地址
        server-addr: localhost:8848
    sentinel:
      transport:
        #配制sentinel dashboard地址
        dashboard: localhost:8080
        port: 8719  #默认8719,假如被占用了会自动从8719开始依次+1扫描。直至找到未被占用的端口

management:
  endpoints:
    web:
      exposure:
        include: '*'
3.2.3 主启动类
@SpringBootApplication
@EnableDiscoveryClient
public class SentinelMain8401 {
    public static void main(String[] args) {
        SpringApplication.run(SentinelMain8401.class,args);
    }
}
3.2.4 业务类FlowLimitController
@RestController
public class FlowLimitController
{
    @GetMapping("/testA")
    public String testA() {
        return "------testA";
    }

    @GetMapping("/testB")
    public String testB() {

        return "------testB";
    }
}

3.3 启动Sentinel8080

java -jar sentinel-dashboard-1.7.0

3.4 启动测试微服务8401

3.5 测试结果

  启动8401微服务后查看sentienl控制台,发现空空如也,啥都没有,并没有微服务注册到控制台进行管理。
  其实原因主要是Sentinel采用的懒加载,执行一次访问即可注册进控制台。

http://localhost:8401/testA
http://localhost:8401/testB

效果:
在这里插入图片描述
可看见sentinel8080正在监控微服务8401。

四、流控规则

4.1 流控模式

4.1.1 直接(默认)

系统默认:直接->快速失败

默认配置说明:

表示1秒钟内查询1次就是OK,若超过次数1,就直接快速失败,报默认错误

在这里插入图片描述

测试:
快速点击访问http://localhost:8401/testA,结果:Blocked by Sentinel (flow limiting)
直接调用默认报错信息,技术方面OK but,是否应该有我们自己的后续处理?即返回自己需要的结果,使用@SentinelResource注解,在后面进行介绍。

4.1.2 关联

  当关联的资源达到阈值时,就限流自己,如当与A关联的资源B达到阈值后,就限流A自己(B惹事,A挂了)。

配置说明
  当关联资源 /testB 的 qps 阀值超过1时,就限流/testA的Rest访问地址, 即当关联资源到阈值后限制配置好的资源名

在这里插入图片描述

4.1.3 链路

多个请求调用了同一个微服务,超过阈值则限流。

例如:一棵典型的调用树如下图所示:
在这里插入图片描述
上图中来自入口 Entrance1 和 Entrance2 的请求都调用到了资源 NodeA,Sentinel 允许只根据某个入口的统计信息对资源限流。比如我们可以设置 strategy 为 RuleConstant.STRATEGY_CHAIN,同时设置 refResource 为 Entrance1 来表示只有从入口 Entrance1 的调用才会记录到 NodeA 的限流统计当中,而不关心经 Entrance2 到来的调用。

调用链的入口(上下文)是通过 API 方法 ContextUtil.enter(contextName) 定义的,其中 contextName 即对应调用链路入口名称。详情可以参考 ContextUtil 文档。

4.2 流控效果

4.2.1 直接->快速失败(默认的流控处理)

直接失败,抛出异常:Blocked by Sentinel (flow limiting)
具体的例子参见 FlowQpsDemo

4.2.2 预热(Warm Up)

公式:阈值除以 coldFactor(默认值为3),经过预热时长后才会达到阈值。
  默认coldFactor为3,即请求QPS从threshold/3开始,经预热时长逐渐升至设定的QPS阈值。即存在一段缓冲时间,不会说突然阈值就很大,导致很多访问进入。
官方文档
具体的例子可以参见 WarmUpFlowDemo
配置说明:
  默认coldFactor为3,即请求QPS从(threshold / 3)开始,经多少预热时长才逐渐升至设定的QPS阈值
案例:阀值为10+预热时长设置5秒。
  系统初始化的阀值为10 / 3约等于3,即阀值刚开始为3;然后过了5秒后阀值才慢慢升高恢复到10

在这里插入图片描述
应用场景:如:秒杀系统在开启的瞬间,会有很多流量上来,很有可能把系统打死,预热方式就是把为了保护系统,可慢慢的把流量放进来,慢慢的把阀值增长到设置的阀值q。

4.2.3 匀速排队等待

匀速排队,阈值必须设置为QPS
  匀速排队方式会严格控制请求通过的间隔时间,也即是让请求以均匀的速度通过,对应的是漏桶算法。详细文档可以参考 流量控制 - 匀速器模式,具体的例子可以参见 PaceFlowDemo

作用:这种方式主要用于处理间隔性突发的流量,例如消息队列。想象一下这样的场景,在某一秒有大量的请求到来,而接下来的几秒则处于空闲状态,我们希望系统能够在接下来的空闲期间逐渐处理这些请求,而不是在第一秒直接拒绝多余的请求。

配置说明:
匀速排队,让请求以均匀的速度通过,阀值类型必须设成QPS,否则无效。
设置含义: /testA每秒1次请求,超过的话就排队等待,等待的超时时间为20000毫秒。
在这里插入图片描述

五、降级规则

  除了流量控制以外,对调用链路中不稳定的资源进行熔断降级也是保障高可用的重要措施之一。由于调用关系的复杂性,如果调用链路中的某个资源不稳定,最终会导致请求发生堆积。Sentinel 熔断降级会在调用链路中某个资源出现不稳定状态时(例如调用超时或异常比例升高),对这个资源的调用进行限制,让请求快速失败,避免影响到其它的资源而导致级联错误。当资源被降级后,在接下来的降级时间窗口之内,对该资源的调用都自动熔断(默认行为是抛出 DegradeException)。

5.1 配置说明

在这里插入图片描述

  • RT (平均响应时间,秒级),平均响应时间超出阈值且在时间窗口内通过的请求>=5, 两个条件同时满足后触发降级,窗口期过后关闭断路器。RT最大4900 (更大的需要通过-Dcsp.sentinel.statistic.max.t=XXXX才能生效)
  • 异常比列(秒级),QPS>= 5且异常比例(秒级统计)超过阈值时,触发降级;时间窗口结束后,关闭降级
  • 异常数(分钟级),异常数(分钟统计)超过阈值时,触发降级;时间窗口结束后,关闭降级

Sentinel的断路器和Hystrix不同是没有半开状态的,半开的状态系统自动去检测是否请求有异常,没有异常就关闭断路器恢复使用,有异常则继续打开断路器不可用。具体可以参考Hystrix

5.2 降级策略

5.2.1 RT

  平均响应时间 (DEGRADE_GRADE_RT):当 1s 内持续进入 N 个请求,对应时刻的平均响应时间(秒级)均超过阈值(count,以 ms 为单位),那么在接下的时间窗口(DegradeRule 中的 timeWindow,以 s 为单位)之内,对这个方法的调用都会自动地熔断(抛出 DegradeException)。注意 Sentinel 默认统计的 RT 上限是 4900 ms,超出此阈值的都会算作 4900 ms,若需要变更此上限可以通过启动配置项 -Dcsp.sentinel.statistic.max.rt=xxx 来配置。
在这里插入图片描述
测试:
编写测试业务方法:

@GetMapping("/testD")
    public String testD()
    {
        try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
        log.info("testD 测试RT");
        return "------testD";
    }

在这里插入图片描述
  按照上述配置,使用Jmeter压测工具永远一秒钟打进来10个线程(大于5个了)调用testD,我们希望200毫秒处理完本次任务,如果超过200毫秒还没处理完,在未来1秒钟的时间窗口内,断路器打开(保险丝跳闸)微服务不可用,保险丝跳闸断电了后续我停止jmeter,没有这么大的访问量了,断路器关闭(保险丝恢复),微服务恢复OK。

5.2.2 异常比例

  异常比例 (DEGRADE_GRADE_EXCEPTION_RATIO):当资源的每秒请求量 >= N(可配置),并且每秒异常总数占通过量的比值超过阈值(DegradeRule 中的 count)之后,资源进入降级状态,即在接下的时间窗口(DegradeRule 中的 timeWindow,以 s 为单位)之内,对这个方法的调用都会自动地返回。异常比率的阈值范围是 [0.0, 1.0],代表 0% - 100%。
在这里插入图片描述
测试:
编写测试业务方法:

@GetMapping("/testD")
    public String testD()
    {
        log.info("异常比例");
        int age = 10/0;
        return "------testD";
    }

在这里插入图片描述
  按照上述配置,单独访问一次,必然来一次报错一次(int age = 10/0), 调一次错一次;开启jmeter后,直接高并发发送请求,多次调用达到我们的配置条件了。断路器开启(保险丝跳闸),微服务不可用了,**不再报错error而是服务降级了。**显示(Blocked by Sentinel (flow limiting)

5.2.3 异常数

  异常数 (DEGRADE_GRADE_EXCEPTION_COUNT):当资源近 1 分钟的异常数目超过阈值之后会进行熔断。注意由于统计时间窗口是分钟级别的,若 timeWindow 小于 60s,则结束熔断状态后仍可能再进入熔断状态。
在这里插入图片描述
测试:
编写测试业务方法:

@GetMapping("/testE")
    public String testE()
    {
        log.info("testE 测试异常数");
        int age = 10/0;
        return "------testE 测试异常数";
    }

在这里插入图片描述
  按以上配置,http://localhost:8401/testE,第一次访问绝对报错,因为除数不能为零,
我们看到error窗口,但是达到5次报错后,进入熔断后降级,显示(Blocked by Sentinel (flow limiting)

注意:异常降级仅针对业务异常,对 Sentinel 限流降级本身的异常(BlockException)不生效。为了统计异常比例或异常数,需要通过 Tracer.trace(ex) 记录业务异常。

六、热点key限流

官网:https://github.com/alibaba/Sentinel/wiki/热点参数限流
  热点参数限流会统计传入参数中的热点参数,并根据配置的限流阈值与模式,对包含热点参数的资源调用进行限流。热点参数限流可以看做是一种特殊的流量控制,仅对包含热点参数的资源调用生效。

兜底方法
分为系统默认和客户自定义两种,之前的case,限流出问题后,都是用sentinel系统默认的提示: Blocked by Sentinel (flow limiting)

我们能不能自定?类似hystrix,某个方法出问题了,就找对应的兜底降级方法?
结论:从HystrixCommand到@SentinelResource

6.1 配置

实现代码:

@GetMapping("/testHotKey")
    @SentinelResource(value = "testHotKey",blockHandler = "deal_testHotKey")
    public String testHotKey(@RequestParam(value = "p1",required = false) String p1,
                             @RequestParam(value = "p2",required = false) String p2) {
        //int age = 10/0;
        return "------testHotKey";
    }

    //兜底方法
    public String deal_testHotKey (String p1, String p2, BlockException exception){
        return "------deal_testHotKey,o(╥﹏╥)o"; //sentinel系统默认的提示: Blocked by Sentinel (fLow limiting)
    }

在这里插入图片描述

  • 方式1:@SentinelResource(value = "testHotKey") ,异常打到了前台用户界面看不到,不友好
  • 方式2:@SentinelResource(value = "testHotKey",blockHandler = "deal_testHotKey") ,方法testHostKey里面第一个参数只要QPS超过每秒1次,马上降级处理,用了我们自己定义的的兜底方法。

6.2 测试

  • http://localhost:8401/testHotKey?p1=abc QPS超过每秒1次,error,返回我们自己写的内容
  • http://localhost:8401/testHotKey?p1=abc&p2=33 QPS超过每秒1次,error,返回我们自己写的内容
  • http://localhost:8401/testHotKey?p2=abc 由于我们配置的是要第一个参数,与第二个参数无关,right

6.3 参数例外项

  上述案例演示了第一个参数p1,当QPS超过1秒1次点击后马上被限流,我们期望p1参数当它是某个特殊值时,它的限流值和平时不一样,假如当p1的值等于5时,它的阈值可以达到200(特例)

6.3.1 配置

在这里插入图片描述

6.3.2 测试
  • http://localhost:8401/testHotKey?p1=5 right,设置了参数例外项,即当QPS超过每秒200次时,才会出现error,返回我们自己写的内容
  • http://localhost:8401/testHotKey?p1=3 QPS超过每秒1次,error,返回我们自己写的内容

热点参数的注意点,参数必须是基本类型或者String

6.4 注意

  @SentinelResource处理的是Sentinel控制台配置的违规情况,有blockHandler方法配置的兜底处理;RuntimeException int age = 10/0, 这个是java运行时报出的运行时异常RunTimeException,@SentinelResource不管

总结:@SentinelResource主管配置出错,运行出错该走异常走异常

七、系统规则

官网:https://github.com/alibaba/Sentinel/wiki/%E7%B3%BB%E7%BB%9F%E8%87%AA%E9%80%82%E5%BA%94%E9%99%90%E6%B5%81
  系统保护规则是从应用级别的入口流量进行控制,从单台机器的 load、CPU 使用率、平均 RT、入口 QPS 和并发线程数等几个维度监控应用指标,让系统尽可能跑在最大吞吐量的同时保证系统整体的稳定性。

系统保护规则是应用整体维度的,而不是资源维度的,并且仅对入口流量生效。入口流量指的是进入应用的流量(EntryType.IN),比如 Web 服务或 Dubbo 服务端接收的请求,都属于入口流量。

7.1 各项配置参数说明

  • Load 自适应(仅对 Linux/Unix-like 机器生效):系统的 load1 作为启发指标,进行自适应系统保护。当系统 load1 超过设定的启发值,且系统当前的并发线程数超过估算的系统容量时才会触发系统保护(BBR 阶段)。系统容量由系统的 maxQps * minRt 估算得出。设定参考值一般是 CPU cores * 2.5
  • CPU usage(1.5.0+ 版本):当系统 CPU 使用率超过阈值即触发系统保护(取值范围 0.0-1.0),比较灵敏。
  • 平均 RT:当单台机器上所有入口流量的平均 RT 达到阈值即触发系统保护,单位是毫秒。
  • 并发线程数:当单台机器上所有入口流量的并发线程数达到阈值即触发系统保护。
  • 入口 QPS:当单台机器上所有入口流量的 QPS 达到阈值即触发系统保护。

7.2 配置全局QPS

直接配置系统负责,选择QPS模式即可。

八、@SentinelResource

8.1 按资源名称限流+后续处理

8.1.1 编写业务类RateLimitController:
@RestController
@Slf4j
public class RateLimitController {
    @GetMapping("/byResource")
    @SentinelResource(value = "byResource",blockHandler = "handleException")
    public CommonResult byResource()
    {
        return new CommonResult(200,"按资源名称限流测试OK",new Payment(2020L,"serial001"));
    }
    public CommonResult handleException(BlockException exception)
    {
        return new CommonResult(444,exception.getClass().getCanonicalName()+"\t 服务不可用");
    }
}
8.1.2 配置步骤

在这里插入图片描述
表示1秒钟内查询次数大于1,就跑到我们自定义的限流兜底方法。

8.1.3 测试

  1秒钟点击1下,OK,超过上述阈值,疯狂点击,返回了自己定义的限流处理信息,限流发送。

8.1.4 额外问题

  此时关闭微服务8401看看,Sentinel控制台,流控规则消失了?????可见配置的流控规则是临时的,需要做持久化处理。

8.2 按照Url地址限流+后续处理

通过访问的URL来限流,会返回Sentinel自带默认的限流处理信息

8.2.1 编写业务类测试方法
@GetMapping("/rateLimit/byUrl")
    @SentinelResource(value = "byUrl")
    public CommonResult byUrl()
    {
        return new CommonResult(200,"按url限流测试OK",new Payment(2020L,"serial002"));
    }
8.2.2 Sentinel控制台配置

在这里插入图片描述

8.2.3 测试

  1秒钟点击1下,OK,超过上述设置阈值,疯狂点击,返回Sentinel自带默认的限流处理信息 Blocked by Sentinel (flow limiting)

8.3 客户自定义限流处理逻辑

8.3.1 上面兜底方法面临的问题
  • 系统默认的,没有体现我们自己的业务要求。
  • 依照现有条件,我们自定义的处理方法汉和业务代码耦合在一块,不直观。
  • 每个业务方法都添加一个兜底的,那代码膨胀加剧。
  • 全局统一的处理方法没有体现。
8.3.2 创建customerBlockHandler类用于自定义限流处理逻辑
public class CustomerBlockHandler {

    public static CommonResult handlerException(BlockException exception) {
        return new CommonResult(2020, "自定义global限流处理信息....CustomerBlockHandler---1");
    }

    public static CommonResult handlerException2(BlockException exception) {
        return new CommonResult(2020, "自定义global限流处理信息....CustomerBlockHandler---2");
    }
}
8.3.3 编写业务类测试方法
blockHandlerClass = CustomerBlockHandler.class //指定限流处理逻辑类
blockHandler = "handlerException2"	//限流处理1类中的特定方法
//使用全局自定义兜底方法,解决代码膨胀和代码耦合
    @GetMapping("/rateLimit/customerBlockHandler")
    @SentinelResource(value = "customerBlockHandler",
            blockHandlerClass = CustomerBlockHandler.class,
            blockHandler = "handlerException2")
    public CommonResult customerBlockHandler()
    {
        return new CommonResult(200,"按客戶自定义",new Payment(2020L,"serial003"));
    }

对应:
在这里插入图片描述

8.3.4 Sentinel控制台配置

在这里插入图片描述

8.3.5 测试

启动微服务后先调用一次:http://localhost:8401/rateLimit/customerBlockHandler,正常;疯狂点击,我们自定义限流处理方法的信息出来了。

8.4 更多注解属性说明

Sentinel主要有三个核心API

  • SphU定义资源
  • Tracer定义统计
  • ContextUtil定义了上下文

九、服务熔断

sentinel整合ribbon+openFeign+fallback

9.1 Ribbon系列

9.1.1 启动nacos和sentinel
9.1.2 新建cloudalibaba-provider-payment9003/9004两个服务提供者

pom 依赖:

<dependencies>
        <!--SpringCloud ailibaba nacos -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency><!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
            <groupId>com.cn.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>${project.version}</version>
        </dependency>
        <!-- SpringBoot整合Web组件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!--日常通用jar包配置-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

yml 配置文件:记得修改不同的端口号

server:
  port: 9003

spring:
  application:
    name: nacos-payment-provider
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #配置Nacos地址

management:
  endpoints:
    web:
      exposure:
        include: '*'

主启动类:

@SpringBootApplication
@EnableDiscoveryClient
public class PaymentMain9003
{
    public static void main(String[] args) {
        SpringApplication.run(PaymentMain9003.class, args);
    }
}

业务类:

@RestController
public class PaymentController
{
    @Value("${server.port}")
    private String serverPort;
	//模拟数据库中的数据
    public static HashMap<Long, Payment> hashMap = new HashMap<>();
    static{
        hashMap.put(1L,new Payment(1L,"28a8c1e3bc2742d8848569891fb42181"));
        hashMap.put(2L,new Payment(2L,"bba8c1e3bc2742d8848569891ac32182"));
        hashMap.put(3L,new Payment(3L,"6ua8c1e3bc2742d8848569891xt92183"));
    }

    @GetMapping(value = "/paymentSQL/{id}")
    public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id){
        Payment payment = hashMap.get(id);
        CommonResult<Payment> result = new CommonResult(200,"from mysql,serverPort:  "+serverPort,payment);
        return result;
    }
}
9.1.3 测试
http://localhost:9003/paymentSQL/1

看是否均能返回数据。

9.1.4 消费者84

新建cloudalibaba-consumer-nacos-order84
pom 依赖:

<dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <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-sentinel</artifactId>
        </dependency>
        <dependency>
            <groupId>com.cn.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

yml 配置:

server:
  port: 84

spring:
  application:
    name: nacos-order-consumer
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
    sentinel:
      transport:
        dashboard: localhost:8080
        #默认8719端口,假如被占用会自动从8719开始依次+1扫描,直至找到未被占用的端口
        port: 8719
#消费者要去访问的微服务名称
service-url:
  nacos-user-service: http://nacos-payment-provider

#激活Sentinel对Feign的支持
feign:
  sentinel:
    enabled: true

主启动类:

@EnableDiscoveryClient
@SpringBootApplication
public class OrderNacosMain84 {
    public static void main(String[] args) {
        SpringApplication.run(OrderNacosMain84.class, args);
    }
}

业务类:
ApplicationContextConfig:

@Configuration
public class ApplicationContextConfig {
    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
}

CircleBreakerController的全部源码:

@RestController
@Slf4j
public class CircleBreakerController {

    public static final String SERVICE_URL = "http://nacos-payment-provider";

    @Resource
    private RestTemplate restTemplate;

    @RequestMapping("/consumer/fallback/{id}")
    //@SentinelResource(value = "fallback") //没有配置
    //@SentinelResource(value = "fallback",fallback = "handlerFallback") //fallback只负责业务异常
    //@SentinelResource(value = "fallback",blockHandler = "blockHandler") //blockHandler只负责sentinel控制台配置违规
    @SentinelResource(value = "fallback",fallback = "handlerFallback",blockHandler = "blockHandler",
            exceptionsToIgnore = {IllegalArgumentException.class})
    public CommonResult<Payment> fallback(@PathVariable Long id) {
        CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/"+id, CommonResult.class,id);

        if (id == 4) {
            throw new IllegalArgumentException ("IllegalArgumentException,非法参数异常....");
        }else if (result.getData() == null) {
            throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
        }

        return result;
    }

    //fallback
    public CommonResult handlerFallback(@PathVariable  Long id,Throwable e) {
        Payment payment = new Payment(id,"null");
        return new CommonResult<>(444,"兜底异常handlerFallback,exception内容  "+e.getMessage(),payment);
    }

    //blockHandler
    public CommonResult blockHandler(@PathVariable  Long id, BlockException blockException) {
        Payment payment = new Payment(id,"null");
        return new CommonResult<>(445,"blockHandler-sentinel限流,无此流水: blockException  "+blockException.getMessage(),payment);
    }


    // OpenFeign

    @Resource
    private PaymentService paymentService;

    @GetMapping(value = "/consumer/paymentSQL/{id}")
    public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id) {
        return paymentService.paymentSQL(id);
    }

}
  • fallback管运行异常
  • blockHandler管配置违规
  • exceptionsToIgnore 假如报该异常,不再有fallback方法兜底,没有降级效果了。

若blockHandler和fallback都进行了配置,则被限流降级而抛出BlockException时只会进入blockHandler处理逻辑。
在这里插入图片描述

9.1.5 测试
http://localhost:84/consumer/fallback/1

可实现负载均衡,上述配置的fallback、blockHandler、exceptionsToIgnore 均测试成功。

9.2 Feign系列

9.2.1 修改84模块

pom:添加依赖

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

yml :添加配置

#对Feign的支持
feign:
  sentinel:
    enabled: true
9.2.2 业务类

创建带@FeignClient注解的业务接口:

@FeignClient(value = "nacos-payment-provider",fallback = PaymentFallbackService.class)
public interface PaymentService {
    @GetMapping(value = "/paymentSQL/{id}")
    public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id);
}

fallback = PaymentFallbackService.class,即兜底方法:

@Component
public class PaymentFallbackService implements PaymentService{
    @Override
    public CommonResult<Payment> paymentSQL(Long id){
        return new CommonResult<>(44444,"服务降级返回,---PaymentFallbackService",new Payment(id,"errorSerial"));
    }
}

controller增加:

// OpenFeign
@Resource
private PaymentService paymentService;

@GetMapping(value = "/consumer/paymentSQL/{id}")
public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id) {
    return paymentService.paymentSQL(id);
}

主启动类:添加@EnableFeignClients启动Feign的功能

@EnableDiscoveryClient
@SpringBootApplication
@EnableFeignClients
public class OrderNacosMain84{
    public static void main(String[] args) {
        SpringApplication.run(OrderNacosMain84.class, args);
    }
}
9.2.4 测试
http://lcoalhost:84/consumer/paymentSQL/1

测试84调用9003,此时故意关闭9003微服务提供者,看84消费费侧自动降级,不会被耗死

9.3 熔断框架比较

在这里插入图片描述

十、规则持久化

问题:一旦我们重启应用,Sentinel规则将消失,生产环境需要将配置规则进行持久化

解决:将限流配置规则持久化进Nacos保存,只要刷新8401某个rest地址,sentinel控制台的流控规则就能看到,只要Nacos里面的配置不删除,针对8401上Sentinel上的流控规则持续有效

步骤

10.1 修改cloudalibaba-sentinel-service8401

pom:添加依赖

<!--后续做持久化操作用到-->
<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-datasource-nacos</artifactId>
</dependency>

yml:添加Nacos数据源配置

server:
  port: 8401

spring:
  application:
    name: cloudalibaba-sentinel-service
  cloud:
    nacos:
      discovery:
        #nacos服务注册中心地址
        server-addr: localhost:8848
    sentinel:
      transport:
        #配制sentinel dashboard地址
        dashboard: localhost:8080
        port: 8719  #默认8719,假如被占用了会自动从8719开始依次+1扫描。直至找到未被占用的端口
      #Nacos数据源配置
      datasource:
        ds1:
          nacos:
            server-addr: localhost:8848
            dataId: cloudalibaba-sentinel-service
            groupId: DEFAULT_GROUP
            data-type: json
            rule-type: flow


management:
  endpoints:
    web:
      exposure:
        include: '*'
feign:
  sentinel:
    enabled: true # 激活Sentinel对Feign的支持

10.2 添加Nacos业务规则配置

在这里插入图片描述
内容解析:
在这里插入图片描述

10.3 测试

  • 启动8401后刷新sentinel发现业务规则有了
  • 快速访问测试接口:http://localhost:8401/rateLimit/byUrl,默认结果:Blocked by Sentinel(f1ow 1imiting)
  • 停止8401再看sentinel
    在这里插入图片描述
  • 重新启动8401再看sentinel,扎一看还是没有,稍等一会儿,多次调用http://localhost:8401/rateLimit/byUrl,重新配置出现了,持久化验证通过

详细代码请看GitHub

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值