springcloud:3.5测试慢调用熔断降级

时间:2024-03-07 15:07:51

 

服务提供者【test-provider8001】

 Openfeign远程调用服务提供者搭建

文章地址http://t.csdnimg.cn/06iz8

相关接口

测试远程调用:http://localhost:8001/payment/index

服务消费者【test-consumer-resilience4j8004】

 Openfeign远程调用消费者搭建

文章地址http://t.csdnimg.cn/06iz8

依赖

 <!-- resilience4j  -->
        <dependency>
            <groupId>io.github.resilience4j</groupId>
            <artifactId>resilience4j-spring-cloud2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-circuitbreaker-resilience4j</artifactId>
        </dependency>

application.yml

resilience4j.circuitbreaker:
  configs:
    default:
      # 熔断器打开的失败阈值
      failureRateThreshold: 30
      # 默认滑动窗口大小,circuitbreaker使用基于计数和时间范围欢动窗口聚合统计失败率
      slidingWindowSize: 10
      # 滑动窗口类型,默认为基于计数的滑动窗口
      slidingWindowType: TIME_BASED
      # 计算比率的最小值,和滑动窗口大小去最小值,即当请求发生5次才会计算失败率
      minimumNumberOfCalls: 5
      # 半开状态允许的请求数
      permittedNumberOfCallsInHalfOpenState: 3
      # 是否自动从打开到半开
      automaticTransitionFromOpenToHalfOpenEnabled: true
      # 熔断器从打开到半开需要的时间
      waitDurationInOpenState: 2s
      recordExceptions:
        - java.lang.Exception
  instances:
    # 异常熔断比例降级
    # 实例名称:自己定义的名称,对应@CircuitBreaker的name
    backendA:
      # 采用上面的default配置
      baseConfig: default
    # 慢调用熔断比例降级
    # 实例名称:自己定义的名称,对应@CircuitBreaker的name
    backendB:
      # 熔断器打开的失败阈值
      failureRateThreshold: 50
      # 慢调用时间阈值,超过两秒就算慢调用
      slowCallDurationThreshold: 2s
      # 慢调用百分比阈值,断路器吧调用事件大于slow
      slowCallRateThreshold: 30
      slidingWindowSize: 10
      slidingWindowType: TIME_BASED
      minimumNumberOfCalls: 2
      permittedNumberOfCallsInHalfOpenState: 2
      waitDurationInOpenState: 2s
      eventConsumerBufferSize: 10

OrderController【控制层】

/**
     * 慢调用比例熔断降级
     *
     * @return
     */
    @GetMapping("/slowcircuitbackend")
    @CircuitBreaker(name = "backendB", fallbackMethod = "slowcircuitbackendFallback")
    public String slowcircuitbackend() {
        log.info("************ 进入方法 ***********");
        //沉睡10秒,触发慢调用
        try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String index = paymentFeignService.paymentIndex();
        log.info("************ 离开方法 ***********");
        return index;
    }

    /**
     * 慢调用比例熔断降级方法
     *
     * @param e
     * @return
     */
    public String slowcircuitbackendFallback(Throwable e) {
        e.printStackTrace();
        return "太慢了,触发慢调用比例熔断降级";
    }

相关接口

测试慢调用比例熔断降级:http://localhost:8004/order/slowcircuitbackend