微服务SpringCloud开弓之SpringCloud Alibaba Sentinel实现熔断与限流「十四」

SpringBoot整合Sentinel springboot 整合 sentinel 简单示例 pom.xml 中添加依赖 <dependency> <groupId>com.alibaba.csp</groupId> <artifactId>sentinel-core</artifactId> <version>1.8.0</version> </dependency> 编写 Controller @Controller p 阅读详情

SpringCloud Alibaba Sentinel实现熔断与限流

1、Sentinel

官网

  • 为什么

在这里插入图片描述

一句话解释,之间我们讲解过的Hystrix

  • 能干嘛

在这里插入图片描述

文档地址

  • 怎么玩:解决那些问题

    服务血崩

    服务降级

    服务熔断

    服务限流

2、安装Sentinel控制台

  • sentinel组件有两部分构成:前台和后台8080

在这里插入图片描述

  • 下载jar包并启动

  • 访问页面
    在这里插入图片描述

3、初始化演示工程

  • 启动8848成功

  • 建Module

    1、cloudalibaba-sentinel-service8401

    2、POM

      <dependencies>
            <dependency><!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
                <groupId>com.atguigu.springcloud</groupId>
                <artifactId>cloud-api-common</artifactId>
                <version>${project.version}</version>
            </dependency>
            <!--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>
            <!--openfeign-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-openfeign</artifactId>
            </dependency>
            <!-- SpringBoot整合Web组件+actuator -->
            <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.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <scope>runtime</scope>
                <optional>true</optional>
            </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、yml

    server:
      port: 8401
    
    spring:
      application:
        name: cloudalibaba-sentinel-service
      cloud:
        nacos:
          discovery:
            server-addr: 192.168.149.102:1111 #Nacos服务注册中心地址
        sentinel:
          transport:
            dashboard: localhost:8080 #配置Sentinel dashboard地址
            port: 8719
    
    management:
      endpoints:
        web:
          exposure:
            include: '*'
    

    4、主启动类

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

    5、业务类FlowLimitController类

    @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";
        }
    }
    
  • 启动sentinel8080

  • 启动微服务8401

  • 启动8401微服务后查看sentinel控制台

    1、sentinel采用的是懒加载说明

    http://localhost:8401/testA

    http://localhost:8401/testB

    2、效果
    在这里插入图片描述

4、流控规则

  • 基本介绍
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

  • 流控模式

    1、默认直接

    ​ 直接–>快速失败

    ​ 配置说明

在这里插入图片描述

测试

1秒钟点击1下,OK

点击超过每秒的访问量,进行流量控制

在这里插入图片描述

2、关联

  • 是什么?

    当关联的资源达到阈值时,就限流自己

    当与A关联的资源B达到阈值后,就限流自己

    B惹事,A挂了

  • 配置A

在这里插入图片描述

  • postman模拟并发密集访问testB

    访问testB成功
    在这里插入图片描述
    postman里新建多线程集合组

在这里插入图片描述
在这里插入图片描述

  • 测试

    大批量线程高并发访问B,导致A失效了

    A挂了

在这里插入图片描述

  • 流控效果

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

    ​ 直接失败,抛出异常 --> Blocked by Sentinel (flow limiting)

    ​ 源码 --> com.alibaba.csp.sentinel.slots.block.flow.controller.DefaultController

    2、预热

    • 说明

      公式:阈值除以coldFactor(默认值为3),经过预热时长后才会达到阈值

    • 官网

      限流 冷启动

在这里插入图片描述
在这里插入图片描述
默认coldFactor为3,即请求QPS从threshold/3开始,经预热时长逐渐升至设定的QPS阈值。

  • 源码

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

在这里插入图片描述

  • Warmup配置
    在这里插入图片描述

  • 测试

    多次点击http://localhost:8401/testB

    刚开始不行,后续慢慢OK

  • 应用场景

在这里插入图片描述

  • 排队等待

    1、匀速排队,阈值必须设置为QPS

    2、官网

在这里插入图片描述
在这里插入图片描述
3、源码

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

4、测试

在这里插入图片描述
在这里插入图片描述

5、降级规则

  • 基本介绍

在这里插入图片描述
在这里插入图片描述

进一步说明

在这里插入图片描述

Sentinel的断路器是没有半开状态的

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

在这里插入图片描述

  • 降级策略实战

    1、RT

    • 是什么

在这里插入图片描述

在这里插入图片描述

  • 测试

    1、代码

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

    2、配置

    2毫秒内处理请求,否则断电,时间窗口1秒后恢复

在这里插入图片描述

3、jmeter

http://localhost:8401/testD

在这里插入图片描述

**启动**

在这里插入图片描述
关闭
在这里插入图片描述

2、异常比例

是什么

在这里插入图片描述
在这里插入图片描述

代码

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

        log.info("testD 测试RT");
        int age = 10/0;
        return "------testD";
    }

配置

在这里插入图片描述
jmeter

并发访问http://localhost:8401/testD大于5个
在这里插入图片描述

结论

在这里插入图片描述

3、异常数

是什么

异常数是按照分钟统计的

在这里插入图片描述

在这里插入图片描述

测试

  • 代码

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

在这里插入图片描述
在这里插入图片描述

6、热点key限流

1、基本介绍

​ 官网

@SentinelResource
在这里插入图片描述
代码

com.alibaba.csp.sentinel.slots.block.BlockException

@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";  
}

@SentinelResource(value = “testHotKey”)

异常打到了前台用户界面看不到,不友好

@SentinelResource(value = “testHotKey”,blockHandler = “deal_testHotKey”)@SentinelResource(value = “testHotKey”,blockHandler = “deal_testHotKey”)

方法testHostKey里面第一个参数只要QPS超过每秒1次,马上降级处理 用了我们自己定义的

配置

在这里插入图片描述
测试

http://localhost:8401/testHotKey?p1=abc error

http://localhost:8401/testHotKey?p1=abc&p2=33 error

http://localhost:8401/testHotKey?p2=abc right

结论

上述案例演示了第一个参数p1,当QPS超过1秒1次点击后马上被限流

2、参数例外项
  • 特殊情况

    超过1秒钟一个后,达到阈值1后马上被限流

    我们期望p1参数当它是某个特殊值时,它的限流值和平时不一样

    假如当p1的值等于5时,它的阈值可以达到200

  • 配置

    添加按钮不能忘
    在这里插入图片描述

  • 测试

    http://localhost:8401/testHotKey?p1=5 通过

    http://localhost:8401/testHotKey?p1=3 失败

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

    当p1不等于5的时候,阈值就是平常的1

  • 前提条件

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

  • 其他
    在这里插入图片描述

7、系统规则

  • 是什么

    官网

  • 各项配置参数说明
    在这里插入图片描述

  • 配置全局QPS

8、@SentinelResource

1、按资源名称限流+后续处理
  • 修改cloudalibaba-sentinel-service8401

  • POM

    <dependency>
        <groupId>com.atguigu.springcloud</groupId>
        <artifactId>cloud-api-common</artifactId>
        <version>${project.version}</version>
    </dependency>
    
  • yml

    server:
      port: 8401
    
    spring:
      application:
        name: cloudalibaba-sentinel-service
      cloud:
        nacos:
          discovery:
            server-addr: localhost:8848
        sentinel:
          transport:
            dashboard: localhost:8080
            port: 8719  #默认8719,假如被占用了会自动从8719开始依次+1扫描。直至找到未被占用的端口
    
    management:
      endpoints:
        web:
          exposure:
            include: '*'
    
  • 业务类RateLimitController

    @RestController
    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 服务不可用");
        }
    
  • 主启动

    @EnableDiscoveryClient
    @SpringBootApplication
    public class MainApp8401
    {
        public static void main(String[] args) {
            SpringApplication.run(MainApp8401.class, args);
        }
    }
    
  • 配置流控规则

    配置步骤

在这里插入图片描述

表示1秒钟内查询次数大于1,就跑到我们自定义的处流,限流

  • 测试

    1秒钟点击1下,OK

    超过上述问题,疯狂点击,返回了自己定义的限流处理信息,限流发送

在这里插入图片描述

  • 额外问题

此时关闭微服务8401看看

Sentinel控制台,流控规则消失了????? 临时的

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

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

业务类RateLimitController

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

控制台配置

在这里插入图片描述
测试:

疯狂点击http://localhost:8401/rateLimit/byUrl
在这里插入图片描述

上面兜底方法存在的问题

在这里插入图片描述

3、客户自定义限流处理逻辑
  • 创建customerBlockHandler类用于自定义限流处理逻辑

  • 自定义限流处理类

在这里插入图片描述

package com.atguigu.springcloud.alibaba.myhandler;

import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.atguigu.springcloud.entities.*;

public class CustomerBlockHandler {

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

    }
}
  • RateLimitController

    @GetMapping("/rateLimit/customerBlockHandler")
    @SentinelResource(value = "customerBlockHandler",
            blockHandlerClass = CustomerBlockHandler.class,
            blockHandler = "handlerException2")
    public CommonResult customerBlockHandler()
    {
        return new CommonResult(200,"按客戶自定义",new Payment(2020L,"serial003"));
    }
     
    
  • 启动微服务后先调用一次

    http://localhost:8401/rateLimit/customerBlockHandler

  • Sentinel控制台配置

在这里插入图片描述

  • 测试

在这里插入图片描述

  • 进一步说明

在这里插入图片描述

4、更多注解属性说明
  • 代码配置

在这里插入图片描述

  • 注解

在这里插入图片描述

  • Sentinel主要有三个核心API

    SphU定义资源

    Tracer定义统计

    ContextUtil定义了上下文

9、服务熔断功能

sentinel整合ribbon+openFeign+fallback

Ribbon系列

1、提供者9003/9004

  • 新建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.atguigu.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.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>
    
    
  • 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);
        }
    }
    
  • 业务类

    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;
        }
    }
    
  • 测试地址

    http://localhost:9003/paymentSQL/1

    2、消费者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.atguigu.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.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>
      
    • 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
      
    • 主启动

      @EnableDiscoveryClient
      @SpringBootApplication
      @EnableFeignClients
      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

      package com.atguigu.springcloud.alibaba.controller;
      
      import com.alibaba.csp.sentinel.annotation.SentinelResource;
      import com.alibaba.csp.sentinel.slots.block.BlockException;
      import com.atguigu.springcloud.alibaba.entities.CommonResult;
      import com.atguigu.springcloud.alibaba.entities.Payment;
      
      import lombok.extern.slf4j.Slf4j;
      import org.springframework.web.bind.annotation.GetMapping;
      import org.springframework.web.bind.annotation.PathVariable;
      import org.springframework.web.bind.annotation.RequestMapping;
      import org.springframework.web.bind.annotation.RestController;
      import org.springframework.web.client.RestTemplate;
      
      import javax.annotation.Resource;
      
      
      @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);
          }
      }
      

      没有任何配置

      @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")
      
          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;
          }
      

      在这里插入图片描述

    忽略属性

    编码(那个业务类下面的CircleBreakerController的全部源码)
    在这里插入图片描述

Feign系列

1、修改84模块

  • pom

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>
    
  • 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
    
    #对Feign的支持
    feign:
      sentinel:
        enabled: true
    

    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

  • PaymentFallbackService实现类

    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);
        }
    }
    
  • 测试

    http://lcoalhost:84/consumer/paymentSQL/1

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

在这里插入图片描述

熔断框架比较

在这里插入图片描述

10、规则持久化

  • 是什么

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

  • 怎么玩

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

  • 步骤

    1、修改cloudalibaba-sentinel-service8401

    2、pom

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

    3、yml

    server:
      port: 8401
    
    spring:
      application:
        name: cloudalibaba-sentinel-service
      cloud:
        nacos:
          discovery:
            server-addr: localhost:8848 #Nacos服务注册中心地址
        sentinel:
          transport:
            dashboard: localhost:8080 #配置Sentinel dashboard地址
            port: 8719
          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的支持
    

    添加了数据源

    spring:
       cloud:
        sentinel:
        datasource:
         ds1:
          nacos:
            server-addr:localhost:8848
            dataid:${spring.application.name}
            groupid:DEFAULT_GROUP
            data-type:json
                rule-type:flow
    

    4、添加Nacos业务规则配置
    在这里插入图片描述
    在这里插入图片描述
    内容解析

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

在这里插入图片描述

5、测试

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

  • 快速访问测试接口

    http://localhost:8401/rateLimit/byUrl

在这里插入图片描述

  • 停止8401再看sentinel

    配置规则消失

  • 重新启动8401再看sentinel

    多次调用 http://localhost:8401/rateLimit/byUrl

    重新配置出现了,持久化验证通过

Springboot项目整合Sentinel 1.接入配置中心的情况下,优先整合配置中心,规则方便看。2.如果规则很少改动或者对于实时性不高,可以选择pull模式,实现简单改动代码量较少,相反就选择push模式。dashboard属于可以选配的一环,毕竟也要不了多少服务器成本。参考:sentinel代码 https://github.com/alibaba/Sentinel/tree/master官方文档 https://github.com/alibaba/Sentinel/wiki。 阅读详情

相关推荐

springboot集成与使用Sentinel

在上一篇中,我们初步了解了Sentinel的基本概念,以及其有关限流方面的基础理论,本篇将通过简单的与框架进行整合,看看Sentinel如何在实际项目中进行使用。

congge 1万+

【SpringCloud19】SpringCloud Alibaba Sentinel实现熔断与限流

SpringCloud Alibaba Sentinel实现熔断与限流

qq_45291280的博客 1359

告别安装烦恼!Orange3 3.38.0 Windows绿色版下载即用,附保姆级汉化与组件配置指南

本文详细介绍了Orange3 3.38.0 Windows绿色版的下载与使用,包括中文汉化、组件配置及高效管理技巧。这款无需安装的数据科学工具特别适合快速验证想法的研究人员和移动办公用户,支持多种数据源和可视化工具,大幅提升工作效率。

weixin_30897233的博客 596

SpringCloud之服务限流与熔断

目录 一、限流 1、为什么会出现限流 2、限流的目的 3、限流的好处 4、实现限流的两种方法 1、令牌桶算法 2、提高带宽 5、Gateway限流的实现 1、导入依赖 2、添加redis配置 3、配置资源类 ...

m0_53151031的博客 2159

图形学常见概念小结

前言:本文记录《unity shader入门精要》和openGL相关学习过程中一些学习要点; 文章目录PBR流程渲染管线细分着色器的底层实现,应用原理常见的色调映射算法openGl和Direct X的区别PBR流程和URP渲染管线Camera loop(剔除)MVP矩阵变换光线追踪前向渲染和延迟渲染shader和材质的区别bloom原理后处理的理解高斯模糊实现原理图像处理中的边缘检测算子 PBR流程 小结:一套基于自然界微平面理论、能量守恒、菲涅尔反射、线性空间等的科学理论所实现的基于物理的渲染系统,包含一

小谁的博客 1163

u3d逆向学习之纯C内存读写与ImGui绘制(Android)

方法:需要在/proc/pid/maps文件查找模块名,一行行遍历所有内存,第一个参数为模块名,第二个参数为索引index(因为该模块会有多个,index为正序遍历第index个该模块),若找到了则使用。32位游戏的指针大小采用4字节,而64位游戏的指针大小采用8字节(这里需要注意),数据地址以16进制存储,使用unsigned long类型 ,该函数只有一个参数,数据地址,返回该地址的指针跳转地址。文件,比较其中的内容是否与传入的包名相同,如果相同,则返回该进程的PID。

zhoujunjie2004的博客 1686

Spring Cloud Alibaba 7 训练营 - 第五天服务熔断和限流

Spring Cloud Alibaba 7 训练营 - 第五天服务熔断和限流

Bii_yu的博客 1006

STM32鱼塘水质监测系统设计与实现

物联网技术在农业领域的应用正逐步深入,其中传感器网络作为关键基础设施,通过实时数据采集与传输实现环境监测。基于STM32微控制器的嵌入式系统因其高性能和低功耗特性,成为物联网终端设备的理想选择。该系统通过DS18B20水温传感器、PH传感器和浊度传感器组成的多参数检测网络,配合4G通信模块实现水质数据的远程监控。在农业物联网场景中,这种解决方案不仅大幅降低了传统人工检测的成本,更能通过实时预警有效预防养殖损失。本文介绍的鱼塘水质监测系统正是这一技术的典型应用,展示了如何通过STM32和常见传感器构建高性价比

weixin_42173218的博客 620

Spring Cloud 限流熔断

限流的核心 高并发三把斧:限流、降级、缓存 限流:限流是通过对并发访问/请求进行限速,或者对一个时间窗口内的请求进行限速来保护系统,一旦达到限制速率则可以拒绝服务、排队或等待、降级等处理,程序中的限流就是限制请求,请求包括客户端发起的请求,应用内服务间的请求,很多平台都有限流,例如我们调用第三方的api的时候,对方都会限制每天最多只能调用几次之类的,当请求量超过系统的最大容量后,访问延迟就会增加,超过峰值的流量会拖累整个系统,出现宕机。因此,需要提前流量控制,对于超过峰值的流量,可以直接拒绝掉或者选择随机

numun的博客 588

DFT实战:如何用Synopsys工具搞定多时钟域Scan Chain设计(附避坑指南)

本文详细解析了使用Synopsys DFT Compiler工具链实现多时钟域Scan Chain设计的全流程,包括时钟混合策略、跨时钟域平衡技巧和实战脚本剖析。通过量产验证的工程实践方案,帮助DFT工程师有效解决复杂SoC设计中的Scan Chain挑战,提升测试效率和质量。

mm9012的博客 1031

一文带你完成ARMv8架构中的cache知识点

【摘要】 在最初开发ARM架构时,处理器的时钟速度和内存的访问速度大致相同。今天的处理器内核要复杂得多,其时钟速度可以快上几个数量级。但是,外部总线和内存设备的频率并没有扩大到同样的程度。有可能实现小块的片上SRAM,它可以以与内核相同的速度运行,但是与标准的DRAM块相比,这种RAM非常昂贵,因为后者的容量可以达到数千倍。在许多基于ARM处理器的系统中,访问外部存储器需要几十甚至几百个内核周期。 cache的技术背景 在最初开发ARM架构时,处理器的时钟速度和内存的访问速度大致相同。今天的处.

ABCCloud的博客 1853

【Spring Cloud】16.SpringCloud Alibaba Sentinel实现熔断与限流

目录1.简介2.安装2.1 下载2.2 安装2.3 访问3.测试3.1 新建cloudalibaba-sentinel-service84013.2 Pom.xml3.3 bootstrap.yml3.4 FlowLimitController.java3.5 MainApp8401.java3.6 运行nacos、sentinel、运行84014.流控规则(流量控制配置)5.降级规则(服务降级熔断器)5.1 RT5.1.1 测试5.1.1.1 修改FlowLimitController.java5.1.1

qq_44859586的博客 246

扣子Coze智能体万字教程:从入门到精通,一文掌握AI工作流搭建

智能体 = 角色设定 + 提示词 + 变量输入一个好提示词的核心是结构、风格和复用性创建后可以一键发布成网页应用、对话助手整个过程0代码,只靠配置,人人可学,人人可用四、进阶一:理解「工作流」的威力如果你已经用扣子创建了几个简单的智能体,比如写个爆款小红书文案、生成一段短视频脚本,那恭喜你已经入门。但如果你还停留在“一个智能体 = 一段提示词”的层级,你离真正的智能体生产力革命,还差一步:学会搭建“工作流”——让多个大模型自动协同完成任务。

互联网架构师笔记 3491

SpringBoot集成sentinel

Sentinel 介绍 随着微服务的流行,服务和服务之间的稳定性变得越来越重要。 Sentinel 以流量为切入点,从流量控制、熔断降级、系统负载保护等多个维度保护服务的稳定性。 Sentinel 具有以下特征: 丰富的应用场景: Sentinel 承接了阿里巴巴近 10 年的双十一大促流量的核心场景,例如秒杀(即突发流量控制在系统容量可以承受的范围)、消息削峰填谷、实时熔断下游不可用应用等。 完备的实时监控: Sentinel 同时提供实时的监控功能。您可以在控制台中看到接入应用的单台机器秒级数据

renhe96421的博客 1万+

解锁RK3588:内核模块签名与安全启动配置全攻略

RK3588作为一款高性能嵌入式SoC芯片,其内核模块签名与安全启动配置是保障系统安全的核心机制。本文详细介绍了RK3588的芯片特性,重点阐述了安全启动的硬件信任链原理和内核模块签名的实现方法。通过具体步骤演示了从密钥生成、模块签名到验证加载的完整流程,并深入解析了安全启动配置的硬件连接、软件工具准备、密钥烧录等关键环节。此外,还提出了防御旁路攻击和动态信任链扩展等高级安全策略,为RK3588在工业控制、智能安防等高安全要求场景中的应用提供了全面的安全解决方案。

远程部署调试 运行安装 项目调试 二次开发 项目技术新 持续迭代 部分源码免费分享 346

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

Sentinel学习笔记

Sentinel

m0_57237237的博客 586

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

SpringBoot实战(十五)集成Alibaba Sentinel(1)

SpringBoot实战(十五)集成Alibaba Sentinel(1)

ACGkaka的博客 2449

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

使用Spring Boot集成Sentinel

使用Spring Boot集成Sentinel 大家好,我是微赚淘客系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿! 一、什么是Sentinel? Sentinel 是阿里巴巴开源的一款流量控制、熔断降级的框架,能够帮助我们解决分布式系统中的流量管理问题。在微服务架构中,服务间的调用复杂度高,Sentinel可以...

weixin_40362692的博客 338

Spring Boot整合Sentinel

Sentinel是一款面向分布式服务架构的流量防护组件,它提供实时的流量监控、流量控制、熔断降级等功能,旨在帮助开发者解决分布式系统中的流量管理问题。Sentinel具备高度的灵活性和可扩展性,使得我们能够在复杂的应用场景中更加自如地进行流量控制。在应用程序中定义需要受到Sentinel保护的资源,可以是方法、接口等。通过// 业务逻辑 return "Hello, Sentinel!// 处理流量控制触发时的逻辑 return "Flow control triggered!} }

技术研究中心 1005

springboot集成Sentinel

2、SentinelConfig配置限流规则。4、配置handler。

baidu_35760874的博客 1374

Springboot应用整合Sentinel实现限流、熔断、降级笔记

可以使用官方的sentinel也可使用进行持久化改造后的Sentinel ,本文基于此进行记录。Sentinel持久化到NacosSentinel版本为Nacos版本为关于网关限流、限流和熔断,我自己总结出来了一套规则,有更好的意见希望大家指正。

chenjian723122704的专栏 5738

springBoot整合Sentinel

1.引入sentinel依赖2)配置控制台3)访问order-service的任意端点打开浏览器,访问,这样才能触发sentinel的监控。然后再访问sentinel的控制台,查看簇点链路,查看当前访问的服务a.流控:流量控制!正在上传…其含义是限制 /order/{orderId}这个资源的单机QPS为1,即每秒只允许1次请求,超出的请求会被拦截并报错。

qq_44798125的博客 2506

springboot整合sentinel

springboot整合sentinel

SampsonKong的博客 3772

实战:Springboot集成Sentinel实现流量控制、熔断降级、负载保护

Sentinel实现流量控制、熔断降级、负载保护的实际使用个人觉得还是比较简单,只需要根据官方文章集成和配置使用即可。sentinel的流量控制和负载保护以及高性能都优于hystrix,并提供可视化控制台。如果在可用性和可靠性较高和重要的服务集群场景中,可以优先考虑sentinel。

勤于笔记,成于点滴。 4945

springboot接入整合sentinel

Sentinel整体项目由多个组件构成,但主要分为sentinel-core和sentinel-dashboard,两者分别作为Sentinel的连接服务和管理控制台。使用Sentinel,我们需要先下载sentinel-dashboard管理控制台,然后在应用中依赖sentinel-core连接管理控制台。按理说整合过程应该非常简单,然而由于版本不匹配等问题网上几个帖子都不能成功整合sentinel,因此把整合过程写在这记录一下。

zhangruien的博客 1780

SpringBoot整合Sentinel【详解】

springboot整合sentinel【详解】

qq_27480007的博客 1514
上一篇: 微服务SpringCloud开弓之SpringCloud Alibaba Nacos服务注册和配置中心「十三」
下一篇: 微服务SpringCloud开弓之SpringCloud Alibaba Seata处理分布式事务「十五」
漂吧
博客等级 码龄8年 15粉丝 38原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值