sentinel熔断与限流

这篇具有很好参考价值的文章主要介绍了sentinel熔断与限流。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

一、sentinel简介

分布式系统的流量防卫兵

sentinel官网地址 添加链接描述
sentinel - github地址 添加链接描述

Sentinel 是什么?

随着微服务的流行,服务和服务之间的稳定性变得越来越重要。Sentinel 以流量为切入点,从流量控制、流量路由、熔断降级、系统自适应过载保护、热点流量防护等多个维度保护服务的稳定性。

Sentinel 具有以下特征:

丰富的应用场景:Sentinel 承接了阿里巴巴近 10 年的双十一大促流量的核心场景,例如秒杀(即突发流量控制在系统容量可以承受的范围)、消息削峰填谷、集群流量控制、实时熔断下游不可用应用等。
完备的实时监控:Sentinel 同时提供实时的监控功能。您可以在控制台中看到接入应用的单台机器秒级数据,甚至 500 台以下规模的集群的汇总运行情况。
广泛的开源生态:Sentinel 提供开箱即用的与其它开源框架/库的整合模块,例如与 Spring Cloud、Apache Dubbo、gRPC、Quarkus 的整合。您只需要引入相应的依赖并进行简单的配置即可快速地接入 Sentinel。同时 Sentinel 提供 Java/Go/C++ 等多语言的原生实现。
完善的 SPI 扩展机制:Sentinel 提供简单易用、完善的 SPI 扩展接口。您可以通过实现扩展接口来快速地定制逻辑。例如定制规则管理、适配动态数据源等。

Sentinel 的主要特性:

sentinel熔断与限流,SpringCloudAlibaba,sentinel

Sentinel安装

1、下载Sentinel控制台程序(jar文件)

Sentinel下载 添加链接描述

sentinel熔断与限流,SpringCloudAlibaba,sentinel
2、将控制台程序上传的Linux服务器, 并且通过命令启动

java -jar sentinel-dashboard-1.8.1.jar
命令: nohup java -jar sentinel-dashboard-1.8.1.jar > sentinel.log 2>&1 & 
该命令可以让jar程序在后台运行
注意:需要服务器预留8080端口

3、访问sentinel控制台程序

http://192.168.195.135:8080
注意:账号密码都为sentinel

sentinel熔断与限流,SpringCloudAlibaba,sentinel

二、sentinel整合工程

新建cloudalibaba-sentinel-service8401微服务

sentinel熔断与限流,SpringCloudAlibaba,sentinel

引入依赖

<!--SpringCloud ailibaba nacos -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!--SpringCloud ailibaba sentinel-datasource-nacos 后续做持久化用到-->
<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
<!--SpringCloud ailibaba sentinel -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

yml配置

server:
  port: 8401

spring:
  application:
    name: cloudalibaba-sentinel-service
  cloud:
    nacos:
      discovery:
        server-addr: 192.168.10.132:8848 #Nacos服务注册中心地址
    sentinel:
      transport:
        dashboard: 192.168.10.132:8081 #配置Sentinel dashboard地址
        port: 8719 #默认8719端口,加入被占用会自动从8719+1扫描,直到找到未被占用的端口


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

feign:
  sentinel:
    enabled: true # 激活SentinelFeign的支持

主启动类添加@EnableDiscoveryClient

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;


@EnableDiscoveryClient
@SpringBootApplication
public class SentinelApp8401 {

    public static void main(String[] args) {
        SpringApplication.run(SentinelApp8401.class, args);
    }
}

业务类

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 流空
 */
@RestController
@Slf4j
public class FlowLimitController {
    @GetMapping("/testA")
    public String testA() {
        return "------testA";
    }
    @GetMapping("/testB")
    public String testB() {
        log.info(Thread.currentThread().getName() + "\t" + "...testB");
        return "------testB";
    }
  }

测试

1.启动sentinel服务
2.启动 cloudalibaba-sentinel-service8401

访问 http://192.168.10.132:8081 查看服务

sentinel熔断与限流,SpringCloudAlibaba,sentinel
因为sentinel采用的是懒加载,所以需要执行一次访问即可
访问

http://localhost:8401/testA

sentinel熔断与限流,SpringCloudAlibaba,sentinel

三、sentinel流控规则

基本介绍

sentinel熔断与限流,SpringCloudAlibaba,sentinel

资源名:唯一名称,默认请求路径

针对来源:Sentinel可以针对调用者进行限流,填写微服务名,指定对哪个微服务进行限流 ,默认default(不区分来源,全部限制)

阈值类型/单机阈值:

QPS(每秒钟的请求数量):当调用该接口的QPS达到了阈值的时候,进行限流;
线程数【关门打狗】:当调用该接口的线程数达到阈值时,进行限流

是否集群:

不需要集群

流控模式:

直接:接口达到限流条件时,直接限流
关联:当关联的资源达到阈值时,就限流自己
链路:只记录指定链路上的流量(指定资源从入口资源进来的流量,如果达到阈值,就可以限流)[api级别的针对来源]

流控效果

快速失败:直接失败,抛异常
Warm Up:即请求 QPS 从 threshold / 3 开始,经预热时长逐渐升至设定的 QPS 阈值
排队等待:匀速排队,让请求以匀速的速度通过,阈值类型必须设置为QPS,否则无效

流控模式

直接(默认)

sentinel熔断与限流,SpringCloudAlibaba,sentinel

快速访问 http://localhost:8401/testA

sentinel熔断与限流,SpringCloudAlibaba,sentinel

关联

当关联的的资源达到阈值时,就限制自己(当与A关联的资源B达到阀值后就限流A自己。)

sentinel熔断与限流,SpringCloudAlibaba,sentinel
使用posaman或者jmter并发访问 testB
sentinel熔断与限流,SpringCloudAlibaba,sentinel
访问testA
sentinel熔断与限流,SpringCloudAlibaba,sentinelB满了导致A不可用

链路

多个请求调用了同一个微服务

流控效果

快速失败

直接抛出异常

Warm Up预热/冷启动方式

官网介绍地址:https://github.com/alibaba/Sentinel/wiki/流量控制

默认 coldFactor 为 3,即请求QPS从(threshold / 3) 开始,经多少预热时长才逐渐升至设定的 QPS 阈值。

设置Warm Up

案例,阀值为10+预热时长设置5秒。
系统初始化的阀值为10 / 3 约等于3,即阀值刚开始为3;然后过了5秒后阀值才慢慢升高恢复到10

sentinel熔断与限流,SpringCloudAlibaba,sentinel使用场景

如:秒杀系统在开启的瞬间,会有很多流量上来,很有可能把系统打死,预热方式就是把为了保护系统,可慢慢的把流量放进来,慢慢的把阀值增长到设置的阀值。

源码在

com.alibaba.csp.sentinel.slots.block.flow.controller.WarmUpController

public WarmUpController(double count, int warmUpPeriodInSec) {
this.construct(count, warmUpPeriodInSec, 3);
}

排队等待

sentinel熔断与限流,SpringCloudAlibaba,sentinel

源码在
com.alibaba.csp.sentinel.slots.block.flow.controller.RateLimiterController

排队等待设置:

匀速排队,让请求以均匀的速度通过,阀值类型必须设成QPS,否则无效
设置含义:/testA每秒1次请求,超过的话就排队等待,等待的超时时间为20000毫秒

sentinel熔断与限流,SpringCloudAlibaba,sentinel在请求A接口上添加日记打印

log.info(Thread.currentThread().getName() + "...TestA");

postman或者jmter设置并发线程
sentinel熔断与限流,SpringCloudAlibaba,sentinel观察日记输出(查看等待输出时间)

输出的时间是随机的,只要看到A后面的资源确实是等待了就可以

2022-09-28 10:27:36.051  INFO 9972 --- [io-8401-exec-10] c.z.s.controller.FlowLimitController     : http-nio-8401-exec-10...TestA
2022-09-28 10:27:38.268  INFO 9972 --- [nio-8401-exec-1] c.z.s.controller.FlowLimitController     : http-nio-8401-exec-1...TestA
2022-09-28 10:27:40.469  INFO 9972 --- [nio-8401-exec-4] c.z.s.controller.FlowLimitController     : http-nio-8401-exec-4...TestA
2022-09-28 10:27:42.653  INFO 9972 --- [nio-8401-exec-6] c.z.s.controller.FlowLimitController     : http-nio-8401-exec-6...TestA
2022-09-28 10:27:44.835  INFO 9972 --- [nio-8401-exec-9] c.z.s.controller.FlowLimitController     : http-nio-8401-exec-9...TestA
2022-09-28 10:27:47.055  INFO 9972 --- [io-8401-exec-10] c.z.s.controller.FlowLimitController     : http-nio-8401-exec-10...TestA
2022-09-28 10:27:49.255  INFO 9972 --- [nio-8401-exec-1] c.z.s.controller.FlowLimitController     : http-nio-8401-exec-1...TestA
2022-09-28 10:27:51.467  INFO 9972 --- [nio-8401-exec-4] c.z.s.controller.FlowLimitController     : http-nio-8401-exec-4...TestA
2022-09-28 10:27:53.653  INFO 9972 --- [nio-8401-exec-6] c.z.s.controller.FlowLimitController     : http-nio-8401-exec-6...TestA
2022-09-28 10:27:55.839  INFO 9972 --- [nio-8401-exec-9] c.z.s.controller.FlowLimitController     : http-nio-8401-exec-9...TestA

三、sentinel降级规则

Sentinel降级简介

Sentinel熔断降级会在调用链路中某个资源出现不稳定状态时(例如调用超时或异常比例升高),对这个资源的调用进行限制,让请求快速失败,避免影响到其它的资源而导致级联错误。

当资源被降级后,在接下来的降级时间窗口之内,对该资源的调用都自动熔断(默认行为是抛出DegradeException)。

RT(平均响应时间,秒级)

平均响应时间 超出阈值且在时间窗口内通过的请求>=5,两个条件同时满足后触发降级窗口期过后关闭断路器

RT最大4900(最大的需要通过-Dcsp.sentinel.statistic.max.rt=XXXX才能生效)

异常比例(秒级)

QPS>=5且异常比例(秒级统计)超过阈值时,触发降级;窗口期结束后,关闭降级。

异常数

异常数(分钟统计)超过阈值时,触发降级;时间窗口期结束后,关闭降级。

Sentinel降级-RT

1.修改子项目(8401)的FlowLimitController

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

2.在sentinel的窗口,设置降级

sentinel熔断与限流,SpringCloudAlibaba,sentinel当一秒钟打进来十个线程来调用testD,我们希望200毫秒处理完本次任务,如果超过200毫秒还没处理完,在未来1秒钟的时间窗口内,断路器打开,服务不可用。

Sentinel降级-异常比例

异常比例:当资源的每秒请求量>=5,并且每秒异常总数占通过量的比值超过阈值之后,资源进入降级状态,即在接下来的时间窗口之内,对这个方法的调用都会自动返回,异常比例的阈值范围[0.0,1.0],代表0%-100%。

1.修改子项目(8401)的FlowLimitController

@GetMapping("/testD")
    public String testD() {
        /*try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        int age = 10/0;
        return "**********testD异常比例***********";
    }

2.新增降级规则

sentinel熔断与限流,SpringCloudAlibaba,sentinel

Sentinel降级-异常数

异常数:当资源近1分钟的异常数目超过阈值滞后进行熔断。由于统计时间窗口是分钟级别的,若时间窗口小于60s,则结束熔断状态后仍可能再进入熔断状态。

时间窗口一定要大于60秒

  1. 修改子项目(8401)的FlowLimitController
@GetMapping("/testE")
    public String testE() {
        int age = 10/0;
        return "********testE异常数********";
    }

运行报错。

2.设置异常数

sentinel熔断与限流,SpringCloudAlibaba,sentinel

sentinel熔断与限流,SpringCloudAlibaba,sentinel

Sentinel热点key

热点参数限流会统计参数中的热点参数,并根据配置的限流阈值与模式,对包含热点参数的资源调用进行限流,热点参数限流可以看作是一种特殊的流量控制,仅包含热点参数的资源调用生效

1.修改子项目(8401)的FlowLimitController

@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) {
        return "*****testHotKey successful**********";
    }
    public String deal_testHotKey(String p1, String p2, BlockException ex){
        return "********deal_testHotKey**********";

    }

2.运行

sentinel熔断与限流,SpringCloudAlibaba,sentinel
3.配置热点规则

sentinel熔断与限流,SpringCloudAlibaba,sentinel
参数索引:对访问的第一个参数进行限流

当每秒访问多次的时候就会进行服务熔断

sentinel熔断与限流,SpringCloudAlibaba,sentinel当把blockHandler参数去掉,一秒一次就会显示成功页面,当一秒访问多次的时候就会直接弹出错误页面(Error Page)。

参数例外项#

普通:超过1秒钟一个之后,达到阈值1后马上被限流
我们希望p1参数当它是摸个特殊值时,它的限流值和平时不一样
假如当p1的值等于5时,它的阈值可以达到200

配置参数例外项
sentinel熔断与限流,SpringCloudAlibaba,sentinel
sentinel熔断与限流,SpringCloudAlibaba,sentinel当p1的值不等于5时,阈值是1

当p1的值等于5时,阈值为200

sentinel熔断与限流,SpringCloudAlibaba,sentinel当代码中有错误它不会去报deal_testHotKey,而是会直接显示错误界面。

Sentinel系统规则

系统自适应限流

Sentinel系统自适应限流从整体维度对应用入口流量控制,结合应用的Load、CPU使用率、总体平均RT、入口QPS和并发线程数等几个维度的监控指标,通过自适应的流控策略、让系统的入口流量和系统的负载达到一个平衡,让系统尽可能跑在最大吞吐量的同时保证系统整体的稳定性。

sentinel熔断与限流,SpringCloudAlibaba,sentinelLoad自适应(仅对Linux/Unix-like机器生效):系统的load作为启发指标,进行自适应系统保护。当系统load超过设定的启发值,且系统当前的并发线程数超过估算的系统容量时才会触发系统保护(BBR阶段)。系统容量有系统的maxQps*minRt估算得出,设定参考值一般是CPU cores * 2.5。

CPU usage(1.5.0+版本):当系统CPU使用率超过阈值即触发系统保护(取值范围0.0-1.0),比较灵敏。

平均RT:当单台机器所有入口流量的平均RT达到阈值即触发系统保护,单位是毫秒

并发线程数:当单台机器所有入口流量的并发线程数达到阈值即触发系统保护

入口QPS:当单台机器上所有入口流量的QPS达到阈值即触发系统保护

sentinel熔断与限流,SpringCloudAlibaba,sentinelSentinelResource配置

修改一个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 服务不可用");
    }

运行8401

sentinel熔断与限流,SpringCloudAlibaba,sentinel
设置限流规则
sentinel熔断与限流,SpringCloudAlibaba,sentinel
sentinel熔断与限流,SpringCloudAlibaba,sentinel
按照Url地址限流

修改RateLimitController

//按照URl限流
    @GetMapping("/rateLimit/byUrl")
    @SentinelResource(value = "byUrl")
    public CommonResult byUrl() {
        return new CommonResult(200,"按Url限流测试OK",new Payment(2020L,"serial002"));
    }

sentinel熔断与限流,SpringCloudAlibaba,sentinel设置限流规则

sentinel熔断与限流,SpringCloudAlibaba,sentinelsentinel熔断与限流,SpringCloudAlibaba,sentinel
上面兜底方案面临的问题

  1. 系统默认的,没有体现我们自己的业务要求。
    2.依照现有条件,我们自定义的处理方法又和业务代码耦合在一块,不直观。
  2. 每个业务方法都添加一个兜底的,那会造成代码膨胀加剧。
  3. 全局统一的处理方法没有体现。

修改一个RateLimitController

//CustomerBlockHandler
    @GetMapping("/rateLimit/customerBlockHandler")
    @SentinelResource(value = "customerBlockHandler",blockHandlerClass = CustomerBlockHandler.class,blockHandler = "handlerException1")
    public CommonResult customerBlockHandler() {
        return new CommonResult(200,"按客户自定义",new Payment(2020L,"serial003"));
    }

新建一个CustomerBlockHandler.java

public class CustomerBlockHandler {
    public static CommonResult handlerException1(BlockException exception){
        return new CommonResult(444,"按客户自定义,global handlerException-------1");
    }
    public static CommonResult handlerException2(BlockException exception){
        return new CommonResult(444,"按客户自定义,global handlerException-------2");
    }
}

配置限流规则

sentinel熔断与限流,SpringCloudAlibaba,sentinelsentinel熔断与限流,SpringCloudAlibaba,sentinel
sentinel熔断与限流,SpringCloudAlibaba,sentinel

四、Sentinel服务熔断Ribbon环境

服务提供者

1.新建子项目(cloudalibaba-provider-payment9003)

2.引入依赖

<dependencies>
        <!--SpringCloud ailibaba nacos -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </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>
        <!--引入自己定义的api通用包-->
        <dependency>
            <groupId>com.my.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>${project.version}</version>
        </dependency>
        <!--日常通用jar包配置-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </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>
        <dependency>
            <groupId>com.atguigu.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>1.0-SNAPSHOT</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

3.配置文件application.yml

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

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

4.主启动类

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

5.新建业务类PaymentController

@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,"从入门到放弃"));
        hashMap.put(2L,new Payment(2L,"从删库到跑路"));
        hashMap.put(3L,new Payment(3L,"从进门到坐牢"));
    }
    @GetMapping("/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;
    }
}

服务消费者

1.新建子项目(cloudalibaba-consumer-nacos-order84)

2.引入依赖

<dependencies>
        <dependency>
            <groupId>com.atguigu.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>${project.version}</version>
        </dependency>
        <!--SpringCloud ailibaba nacos -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </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>
        <!--SpringCloud ailibaba sentinel -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>
        <!--日常通用jar包配置-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </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.application.yml配置文件

server:
  port: 84

spring:
  application:
    name: nacos-order-consumer
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
    sentinel:
      transport:
        dashboard: localhost:8080
        port: 8719

service-url:
  nacos-user-service: http://nacos-payment-provider

4.创建主启动类OrderNacosMain84

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

5.负载均衡配置类ApplicationContextConfig

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

6.创建业务类CircleBreakerController

public class CircleBreakerController {
    public static final String SERVICE_URL = "http://nacos-payment-provider";
    @Resource
    private RestTemplate restTemplate;
    @RequestMapping("/consumer/fallback/{id}")
    @SentinelResource(value = "fallback")
    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("非法参数,异常");
        }else if(result.getData()==null) {
            throw new NullPointerException("该ID没有对应的记录,空指针异常");
        }
        return result;
    }
}

Sentinel服务熔断配置fallback

在子项目84上业务类CircleBreakerController加上兜底方法

@RestController
public class CircleBreakerController {
    public static final String SERVICE_URL = "http://nacos-payment-provider";
    @Resource
    private RestTemplate restTemplate;
    @RequestMapping("/consumer/fallback/{id}")
    @SentinelResource(value = "fallback",fallback = "handerFallback")
    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("非法参数,异常");
        }else if(result.getData()==null) {
            throw new NullPointerException("该ID没有对应的记录,空指针异常");
        }
        return result;
    }
    public CommonResult handlerFallback(@PathVariable Long id,Throwable e) {
        Payment payment = new Payment(id, null);
        return new CommonResult<>(444,"兜底异常,异常内容:"+e.getMessage(),payment);
    }
}

sentinel熔断与限流,SpringCloudAlibaba,sentinel
sentinel熔断与限流,SpringCloudAlibaba,sentinelfallback只负责业务异常。

Sentinel服务熔断配置blockhandler

修改子项目84上业务类CircleBreakerController

@RestController
public class CircleBreakerController {
    public static final String SERVICE_URL = "http://nacos-payment-provider";
    @Resource
    private RestTemplate restTemplate;
    @RequestMapping("/consumer/fallback/{id}")
    //@SentinelResource(value = "fallback",fallback = "handerFallback") //fallback只处理业务出现异常
    @SentinelResource(value = "fallback",blockHandler = "blockHandler") //blockHandler只负责sentinel控制台配置违规
    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("非法参数,异常");
        }else if(result.getData()==null) {
            throw new NullPointerException("该ID没有对应的记录,空指针异常");
        }
        return result;
    }
    /*public CommonResult handlerFallback(@PathVariable Long id,Throwable e) {
        Payment payment = new Payment(id, null);
        return new CommonResult<>(444,"兜底异常,异常内容:"+e.getMessage(),payment);
    }*/
    public CommonResult handlerFallback(@PathVariable Long id, BlockException blockException) {
        Payment payment = new Payment(id, null);
        return new CommonResult<>(445, "blockHandler-sentinel限流,无此流水:" + blockException.getMessage(), payment);
    }
}

添加降级规则

sentinel熔断与限流,SpringCloudAlibaba,sentinel
sentinel熔断与限流,SpringCloudAlibaba,sentinel
sentinel熔断与限流,SpringCloudAlibaba,sentinelblockHandler只负责sentinel控制台配置违规
Sentinel服务熔断配置fallback和blockhandler#

若blockHandler和fallback都进行了配置,则被限流降级而抛出BlockException时只会进入blockHandler处理逻辑。

Sentinel服务熔断exceptionsTolgnore

修改子项目84上业务类CircleBreakerController

@RestController
public class CircleBreakerController {
    public static final String SERVICE_URL = "http://nacos-payment-provider";
    @Resource
    private RestTemplate restTemplate;
    @RequestMapping("/consumer/fallback/{id}")
    //@SentinelResource(value = "fallback",fallback = "handerFallback") //fallback只处理业务出现异常
    //@SentinelResource(value = "fallback",blockHandler = "blockHandler") //blockHandler只负责sentinel控制台配置违规
    //@SentinelResource(value = "fallback",fallback = "handerFallback",blockHandler = "blockHandler")
    @SentinelResource(value = "fallback",fallback = "handerFallback",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("非法参数,异常");
        }else if(result.getData()==null) {
            throw new NullPointerException("该ID没有对应的记录,空指针异常");
        }
        return result;
    }
    public CommonResult handlerFallback(@PathVariable Long id,Throwable e) {
        Payment payment = new Payment(id, null);
        return new CommonResult<>(444,"兜底异常,异常内容:"+e.getMessage(),payment);
    }
    public CommonResult handlerFallback(@PathVariable Long id, BlockException blockException) {
        Payment payment = new Payment(id, null);
        return new CommonResult<>(445, "blockHandler-sentinel限流,无此流水:" + blockException.getMessage(), payment);
    }
}

运行

sentinel熔断与限流,SpringCloudAlibaba,sentinel
假如4报异常,不再有fallback方法兜底,没有降级效果了。

五、 Sentinel服务熔断OpenFeign

修改子项目(84)

pom.xml

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

修改application.yml

# 激活SentinelFeign的支持
feign:
  sentinel:
    enabled: true

在主启动类上面加上注解,开启Feign

@EnableFeignClients

创建service接口

@FeignClient(value = "nacos-payment-provider",fallback = PaymentFallbackService.class)
public interface PaymentService {

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

创建接口实现类PaymentFallbackService

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

在业务类CirleBreakerController添加

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

运行

当9003停止运行后,84会

sentinel熔断与限流,SpringCloudAlibaba,sentinel

六、Sentinel持久化规则#

一旦我们重启应用,sentinel规则将会消失,生产环境需要将配置规则进行持久化。

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

修改子项目(8401)

application.yml

server:
  port: 8401

spring:
  application:
    name: cloudalibaba-sentinel-service
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
    sentinel:
      transport:
        dashboard: localhost:8080       #配置Sentinel dashboard地址
        port: 8719      #默认8719端口,如果被占用会自动从8719开始依次+1,直到找到未被占用的端口
                       #8719端口是应用和Sentinel控制台交互的端口
        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: '*'

在nacos里面新建配置
sentinel熔断与限流,SpringCloudAlibaba,sentinel
resource:资源名称;

limitApp:来源应用;

grade:阈值类型,0表示线程数、1表示QPS;

count:单机阈值;

strategy:流控模式,0表示直接,1表示关联,2表示链路;

controlBehavior:流控效果,0表示快速失败,1表示Warm up,2表示排队等待;

clusterMode:是否集群;

启动8401后刷新sentinel发现业务规则有了

sentinel熔断与限流,SpringCloudAlibaba,sentinel文章来源地址https://www.toymoban.com/news/detail-787196.html

到了这里,关于sentinel熔断与限流的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 微服务韧性工程:利用Sentinel实施有效服务容错与限流降级

            目录 一、雪崩效应 二、Sentinel 服务容错         2.1 Sentinel容错思路         2.2 内部异常兼容         2.3 外部流量控制 三、Sentinel 项目搭建 四、Sentinel 工作原理         服务容错是微服务设计中一项重要原则和技术手段,主要目标是在服务出现故障、网络波

    2024年03月15日
    浏览(73)
  • Sentinel 降级、限流、熔断

    在现代分布式系统中,如何有效地保护系统免受突发流量和故障的影响,是每个开发人员和架构师都需要思考的重要问题。在这样的背景下,Sentinel作为一个强大的系统保护和控制组件,为我们提供了降级、限流、熔断等多种策略,帮助我们更好地保障系统的稳定性和可用性

    2024年01月24日
    浏览(32)
  • Sentinel限流、熔断

            sentinel 提供了两种不同的隔离机制:信号量隔离和线程池隔离,它们的主要区别如下: 信号量隔离(Semaphore Isolation) : 原理 :信号量隔离基于计数器(或称令牌桶)的概念。对某个资源设置一个并发访问的最大数量(信号量大小),当请求到达时,如果当前信

    2024年01月18日
    浏览(25)
  • 熔断、限流、降级 —— SpringCloud Alibaba Sentinel

    Sentinel 是阿里中间件团队开源的,面向分布式服务架构的高可用流量防护组件,主要以流量为切入点,从限流、流量整形、熔断降级、系统负载保护、热点防护等多个维度来帮助开发者保障微服务的稳定性 Sentinel 提供了两个服务组件: Sentinel 用来实现微服务系统中服务熔断

    2024年02月08日
    浏览(52)
  • 基于SpringCloudAlibaba+Sentinel的分布式限流设计

    胡弦,视频号2023年度优秀创作者,互联网大厂P8技术专家,Spring Cloud Alibaba微服务架构实战派(上下册)和RocketMQ消息中间件实战派(上下册)的作者,资深架构师,技术负责人,极客时间训练营讲师,四维口袋KVP最具价值技术专家,技术领域专家团成员,2021电子工业出版社年度优

    2024年04月22日
    浏览(25)
  • SpringCloudAlibaba微服务实战系列(四)Sentinel熔断降级、异常fallback、block细致处理

    接着上篇文章的内容,在Sentinel中如何进行降级和熔断呢? 降级规则 在Sentinel中降级主要有三个策略:RT、异常比例、异常数,也是针对某个资源的设置。而在 1.8.0+ 版本后RT改为了 慢调用比例 需要设置允许的慢调用 RT(即最大的响应时间),请求的响应时间大于该值则统计

    2024年02月16日
    浏览(34)
  • SpringMvc集成开源流量监控、限流、熔断降级、负载保护组件Sentinel

    前言:作者查阅了Sentinel官网、51CTO、CSDN、码农家园、博客园等很多技术文章都没有很准确的springmvc集成Sentinel的示例,因此整理了本文,主要介绍SpringMvc集成Sentinel 随着微服务的流行,服务和服务之间的稳定性变得越来越重要。Sentinel 是面向分布式、多语言异构化服务架构的

    2024年02月05日
    浏览(52)
  • 【Spring Cloud】Sentinel流量限流和熔断降级的讲解

    🎉🎉欢迎来到我的CSDN主页!🎉🎉 🏅我是Java方文山,一个在CSDN分享笔记的博主。📚📚 🌟推荐给大家我的专栏《Spring Cloud》。🎯🎯 👉点击这里,就可以查看我的主页啦!👇👇 Java方文山的个人主页 🎁如果感觉还不错的话请给我点赞吧!🎁🎁 💖期待你的加入,一起

    2024年01月23日
    浏览(37)
  • 商城-学习整理-高级-商城业务-Sentinel&限流&熔断&降级&Sleuth+Zipkin链路追踪(二十二)

    什么是熔断 A 服务调用 B 服务的某个功能,由于网络不稳定问题,或者 B 服务卡机,导致功能时间超长。如果这样子的次数太多。我们就可以直接将 B 断路了(A 不再请求 B 接口),凡是调用 B 的直接返回降级数据,不必等待 B 的超长执行。 这样 B 的故障问题,就不会级联影

    2024年02月11日
    浏览(33)
  • 聊一聊服务治理三板斧:限流、熔断、降级和go-sentinel的实现

    我们知道,对于一个项目之初,我们不可能上来就按几千的并发去配置,为什么?两个方面,第一个是成本高。第二个是维护难度大。即便是天猫淘宝这种,也是采用的动态扩容的方式来应对双十一。那么一个项目如何应对突然的高并发,我们有哪些常用的措施和处理呢?我

    2024年01月19日
    浏览(35)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包