首页 > 其他分享 >SpringCloud系列之(七)服务降级

SpringCloud系列之(七)服务降级

时间:2024-02-28 10:45:41浏览次数:28  
标签:服务 降级 系列 hystrix SpringCloud springframework import org id

服务降级

一、Hystrix断路器

1. 概述

1.1 分布式系统面临的问题

复杂分布式体系结构中的应用程序有数十个依赖关系,每个依赖关系在某些时候将不可避免地失败。

![](https://gitee.com/honourer/picturebed/raw/master/SpringCloud/图像 (16).png)

服务雪崩
​ 多个微服务之间调用的时候,假设微服务A调用微服务B和微服务C,微服务B和微服务C又调用其它的微服务,这就是所谓的”扇出”。如果扇出的链路上某个微服务的调用响应时间过长或者不可用,对微服务A的调用就会占用越来越多的系统资源【占满CPU和内存】,进而引|起系统崩溃,所谓的“雪崩效应”.【实际就是服务的高可用受到了破坏】
​ 对于高流量的应用来说,单一的后端依赖可能会 导致所有服务器上的所有资源都在几秒钟内饱和。比失败更糟糕的是,这些应用程序还可能导致服务之间的延迟增加,备份队列,线程和其他系统资源紧张,导致整个系统发生更多的级联故障。这些都表示需要对故障和延迟进行隔离和管理,以便单个依赖关系的失败,不能取消整个应用程序或系统。
​ 通常当你发现一个模块下的某个实例失败后,这时候这个模块依然还会接收流量,然后这个有问题的模块还调用了其他的模块,这样就会发生级联故障,或者叫雪崩。

1.2 是什么

​ Hystrix是一个用于处理分布式系统的延迟和容错的开源库,在分布式系统里,许多依赖不可避免的会调用失败,比如超时、异常等,
​ Hystrix能够保证在一个依赖出问题的情况下, 不会导致整体服务失败,避免级联故障,以提高分布式系统的弹性。
​ "断路器”本身是一种开关装置【保险丝】,当某个服务单元发生故障之后,通过断路器的故障监控(类似熔断保险丝), 向调用方返回一个符合预期的、可处理的备选响应(FallBack),而不是长时间的等待或者抛出调用方无法处理的异常,这样就保证了服务调用方的线程不会被长时间、不必要地占用,从而避免了故障在分布式系统中的蔓延,乃至雪崩。

1.3 能干嘛

服务降级【FullBack】

服务熔断

接近实时的监控【图形化服务监控HystrixDashboard】

服务限流

服务隔离

......

1.4 官网资料

https://github.com/Netflix/Hystrix/wiki/How-To-Use

1.5 Hystrix官宣,停更进维

被动修复bugs,不再接受合并请求,不再发布新版本

2. Hystrix重要概念

2.1 服务降级【Fallback】

当某个服务单元发生故障之后,通过断路器的故障监控(类似熔断保险丝), 向调用方返回一个符合预期的、可处理的备选响应

哪些情况会触发降级

程序运行异常

超时

服务熔断触发服务降级

线程池/信号量打满也会导致服务降级

2.2 服务熔断【Break】

​ 达到最大服务访问后,直接拒绝访问,拉闸限电【保险丝】,然后调用服务降级的方法并返回友好提示

​ 服务的降级->进而熔断->恢复调用链路

2.3 服务限流【Flowlimit】

​ 秒杀、高并发等操作,严禁一窝蜂的过来拥挤,大家排队,一秒钟N个,有序进行

3. Hystrix案例

3.1 构建测试平台

  1. 建Module【cloud-provider-hystrix-payment8001】

  2. 改POM

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <parent>
            <artifactId>cloud2020</artifactId>
            <groupId>com.atguigu.springcloud</groupId>
            <version>1.0-SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>
    
        <artifactId>cloud-provider-hystrix-payment8001</artifactId>
        <dependencies>
            <!--Hystrix-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-client</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>
    
  3. 写YML

    server:
      port: 8001
    
    spring:
      application:
        name: cloud-provider-hystrix-payment
    
    eureka:
      client:
        register-with-eureka: true
        fetch-registry: true
        service-url:
          # 这里是单机版的Eureka Server
          defaultZone: http://eureka7001.com:7001/eureka
    
  4. 主启动

    package com.atguigu.springcloud;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
    
    @SpringBootApplication
    @EnableEurekaClient
    public class PaymentHystrixMain8001 {
        public static void main(String[] args) {
            SpringApplication.run(PaymentHystrixMain8001.class, args);
        }
    }
    
  5. 业务类

    Service【这里为节约时间直接写的类,没有写接口】

    package com.atguigu.springcloud.service;
    
    import org.springframework.stereotype.Service;
    
    import java.util.concurrent.TimeUnit;
    
    @Service
    public class PaymentService {
        /**
         * 简单业务方法
         * @param id
         * @return
         */
        public String paymentInfo_OK(Integer id){
            return "线程池:" + Thread.currentThread().getName() + "\t" + "paymentInfo_OK,id=" + id + "\t" + "O(∩_∩)O哈哈~";
        }
    
        /**
         * 复杂业务方法
         * @param id
         * @return
         */
        public String paymentInfo_Timeout(Integer id){
            int timeNumber = 3;
            try {
                TimeUnit.SECONDS.sleep(timeNumber);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "线程池:" + Thread.currentThread().getName() + "\t" + "paymentInfo_Timeout,id=" + id + "\t" + "O(∩_∩)O哈哈~" + "\t" + "耗时(秒):" + timeNumber;
        }
    }
    

    Controller

    package com.atguigu.springcloud.controller;
    
    import com.atguigu.springcloud.service.PaymentService;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RestController;
    
    import javax.annotation.Resource;
    
    @RestController
    @Slf4j
    public class PaymentController {
        @Resource
        private PaymentService paymentService;
    
        @Value("${server.port}")
        private String port;
    
        @GetMapping("/payment/hystrix/ok/{id}")
        public String paymentInfo_OK(@PathVariable("id") Integer id){
    
            String result = paymentService.paymentInfo_OK(id);
            log.info("*****result:" + result);
            return result;
        }
    
        @GetMapping("/payment/hystrix/timeout/{id}")
        public String paymentInfo_Timeout(@PathVariable("id") Integer id){
    
            String result = paymentService.paymentInfo_Timeout(id);
            log.info("*****result:" + result);
            return result;
        }
    }
    
  6. 正常测试

    先启动eureka7001

    再启动cloud-provider-hystrix-payment8001

    访问http://localhost:8001/payment/hystrix/ok/31,能够正常访问

    访问http://localhost:8001/payment/hystrix/timeout/31,能够正常访问

    至此,测试平台构建完毕,按照正确->错误->降级熔断->恢复的流程演示Hystrix断路器的功能。

3.2 高并发测试

3.2.1 Jmeter压测测试

开启Jmeter,来20000个并发压死8001,20000个请求都去访问paymentInfo_TimeOut服务

注:Jmeter的安装及配置参考【Windows 工具使用指南.md 二十五、Jmeter 5.5】

创建线程组

设置线程组及线程属性

创建HTTP请求

配置HTTP请求

开启/停止压测

压测结果

​ 20000个并发打到http://localhost:8001/payment/hystrix/timeout/31接口上之后,不仅http://localhost:8001/payment/hystrix/timeout/31接口的响应时间变长,http://localhost:8001/payment/hystrix/ok/31接口的响应时间也变长了

压测结果分析

http://localhost:8001/payment/hystrix/timeout/31接口和http://localhost:8001/payment/hystrix/ok/31接口是在同一个微服务中的两个服务,由于20000个并发都打到http://localhost:8001/payment/hystrix/timeout/31接口上,服务器资源都被调来处理这部分高并发请求了,就会导致访问http://localhost:8001/payment/hystrix/ok/31接口也会出现卡顿、延时的现象。【tomcat的默认的工作线程数(SpringBoot集成了Tomcat,Tomcat的线程池默认是10,20000个请求打到http://localhost:8001/payment/hystrix/timeout/31接口上,Tomcat线程池中的10个线程就都被占满了,这就导致此时访问该微服务的其他接口地址响应也会变慢)被打满了,没有多余的线程来分解压力和处理。】

3.2.2 Jmeter压测结论

​ 上面还只是服务提供者8001自己测试,假如此时外部的消费者80也来访问,那消费者只能干等,最终导致消费端80不满意,服务端8001直接被拖死

3.2.3 加入服务消费者进行二次压测

注:Hystrix可以用在服务侧和消费侧,但一般只用在消费侧

  1. 建Module【cloud-consumer-feign-hystrix-order80】

  2. 改POM

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <parent>
            <artifactId>cloud2020</artifactId>
            <groupId>com.atguigu.springcloud</groupId>
            <version>1.0-SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>
    
        <artifactId>cloud-consumer-feign-hystrix-order80</artifactId>
        <dependencies>
            <!--Hystrix-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
            </dependency>
            <!--openfeign-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-openfeign</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-client</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>
    
    </project>
    
  3. 写YML

    server:
      port: 80
    
    spring:
      application:
        name: cloud-provider-hystrix-order
    
    eureka:
      client:
        register-with-eureka: true
        fetch-registry: true
        service-url:
          defaultZone: http://eureka7001.com:7001/eureka/
    
    ribbon:
      #指的是建立连接所用的时间,适用于网络状况正常的情况下,两端连接所用的时间(5s)
      ReadTimeout: 5000
      #指的是建立连接后从服务器读取到可用资源所用的时间(5s)
      ConnectTimeout: 5000
    
  4. 主启动

    package com.atguigu;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.openfeign.EnableFeignClients;
    
    @SpringBootApplication
    @EnableFeignClients
    public class OrderHystrixMain80 {
        public static void main(String[] args) {
            SpringApplication.run(OrderHystrixMain80.class, args);
        }
    }
    
  5. 业务类

    Service

    package com.atguigu.service;
    
    import org.springframework.cloud.openfeign.FeignClient;
    import org.springframework.stereotype.Component;
    import org.springframework.stereotype.Service;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    
    @Component
    @FeignClient("CLOUD-PROVIDER-HYSTRIX-PAYMENT")
    public interface PaymentHystrixService {
    
        @GetMapping("/payment/hystrix/ok/{id}")
        public String paymentInfo_OK(@PathVariable("id") Integer id);
    
        @GetMapping("/payment/hystrix/timeout/{id}")
        public String paymentInfo_Timeout(@PathVariable("id") Integer id);
    }
    

    Controller

    package com.atguigu.controller;
    
    import com.atguigu.service.PaymentHystrixService;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RestController;
    
    import javax.annotation.Resource;
    
    @RestController
    public class OrderHystrixController {
        @Resource
        private PaymentHystrixService paymentHystrixService;
    
        @GetMapping("/consumer/payment/hystrix/ok/{id}")
        public String paymentInfo_OK(@PathVariable("id") Integer id){
            return paymentHystrixService.paymentInfo_OK(id);
        }
    
        @GetMapping("/consumer/payment/hystrix/timeout/{id}")
        public String paymentInfo_Timeout(@PathVariable("id") Integer id){
            return paymentHystrixService.paymentInfo_Timeout(id);
        }
    }
    
  6. 正常测试

    启动EurekaMain7001

    启动PaymentHystrixMain8001

    启动OrderHystrixMain80

    访问http://localhost/consumer/payment/hystrix/ok/31,正常访问,响应速度也很快

  7. 高并发测试

    ​ 20000个并发打到http://localhost:8001/payment/hystrix/timeout/31,然后访问http://localhost/consumer/payment/hystrix/ok/31,响应速度很慢,有时还会出现请求超时的情况。

  8. 故障现象和导致原因

    ​ 8001同一层次的其他接口服务被困死,因为tomcat线程里面的工作线程已经被挤占完毕,80此时调用8001,客户端访问响应缓慢,转圈圈。

  9. 结论

    ​ 正因为有上述故障或不佳表现,才有我们的降级/容错/限流等技术诞生

3.3 降级容错解决的维度要求

超时导致服务器变慢(转圈)【超时不再等待】

出错(宕机或程序运行出错)【出错要有兜底】

对方服务(8001)超时了,调用者(80)不能一直卡死等待,必须有服务降级

对方服务(8001)down机了,调用者(80)不能一直卡死等待,必须有服务降级

对方服务(8001)OK,调用者(80)自己出故障或有自我要求(自己的等待时间小于服务提供者),自己处理降级

3.4 服务降级

​ 服务降级既可以放在服务侧【服务端】,也可以放在消费侧【客户端】,通常放在消费侧【客户端】。

3.4.1 服务侧服务降级

​ 服务侧的服务在执行自身的业务逻辑所花费的时间特别长,迟迟没有响应或者服务侧的服务在执行自身业务逻辑时本身就存在运行错误,就要用到服务侧服务降级,设置自身调用超时时间的峰值,峰值内可以正常运行,超过了峰值需要有兜底的方法处理。

  1. 业务类启用【PaymentHystrixMain8001】
package com.atguigu.springcloud.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class PaymentService {
    /**
     * 简单业务方法
     * @param id
     * @return
     */
    public String paymentInfo_OK(Integer id){
        return "线程池:" + Thread.currentThread().getName() + "\t" + "paymentInfo_OK,id=" + id + "\t" + "O(∩_∩)O哈哈~";
    }

    /**
     * 复杂业务方法
     * @param id
     * @return
     */
    // 通过@HystrixCommand注解实现服务降级
    // fallbackMethod:如果@HystrixCommand标注的方法超时/程序运行出错,由Hystrix调用fallbackMethod指定的方法
    //                 一旦调用服务方法失败并抛出了错误信息后,会自动调用@HystrixCommand标注好的fallbackMethod调用类中的指定方法
    // @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
    //                 设定线程超时时间的峰值为3s,3s以内正常执行,超过3s执行兜底方法
    // 服务提供者和服务消费者都可通过@HystrixCommand配置服务降级
    // 我们自己配置过的热部署方式【Devtools】对java代码的改动明显,但对@HystrixCommand内属性的修改建议重启微服务,Devtools可能不能及时监测到。
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeoutHandler",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
    })
    public String paymentInfo_Timeout(Integer id){
        // 不管是超时异常还是运行异常,只要是服务不可用了,就会触发服务降级,执行兜底方案。
        // int age = 10/0;
        int timeNumber = 5;
        try {
            TimeUnit.SECONDS.sleep(timeNumber);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池:" + Thread.currentThread().getName() + "\t" + "paymentInfo_Timeout,id=" + id + "\t" + "O(∩_∩)O哈哈~" + "\t" + "耗时(秒):" + timeNumber;
    }

    // 定义服务降级的兜底方法
    public String paymentInfo_TimeoutHandler(Integer id){
        // 线程池:HystrixTimer-1 paymentInfo_TimeoutHandler,id=31 o(╥﹏╥)o
        // 当触发服务降级时,调用兜底方法的线程是Hystrix的线程池单独进行处理的,起到了一定的隔离效果。
        return "线程池:" + Thread.currentThread().getName() + "\t" + "paymentInfo_TimeoutHandler,id=" + id + "\t" + "o(╥﹏╥)o";
    }
}
  1. 主启动类激活【PaymentHystrixMain8001】:主启动类中添加注解@EnableCircuitBreaker

当服务不可用时【超时异常/运行异常】,Hystrix就会执行兜底方案

3.4.2 消费侧服务降级

​ 服务侧中某个服务的正常执行时间为5s,而消费侧默认1s内收不到来自服务侧的处理结果就认为超时,这种情况下就可以为消费侧设置服务降级。

  1. YML中开启
# 用于服务降級,在注解@FeignClient中添加fallbackFactory属性值
feign:
  hystrix:
    enabled: true #如果处理自身的容错就开启。开启方式与生产端不一样。
  1. 主启动类中添加注解@EnableHystrix
  2. 业务类【Controller】
package com.atguigu.controller;

import com.atguigu.service.PaymentHystrixService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class OrderHystrixController {
    @Resource
    private PaymentHystrixService paymentHystrixService;

    @GetMapping("/consumer/payment/hystrix/ok/{id}")
    public String paymentInfo_OK(@PathVariable("id") Integer id){
        return paymentHystrixService.paymentInfo_OK(id);
    }

    // 只要@HystrixCommand标注的方法不可用【超时/运行异常】,服务降级方法就会被执行
    @GetMapping("/consumer/payment/hystrix/timeout/{id}")
    @HystrixCommand(fallbackMethod = "paymentInfoTimeoutFallbackMethod",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "1500")
    })
    public String paymentInfo_Timeout(@PathVariable("id") Integer id){
        return paymentHystrixService.paymentInfo_Timeout(id);
    }

    public String paymentInfoTimeoutFallbackMethod(@PathVariable("id") Integer id){
        return "我是消费者80,对方支付系统繁忙请10秒钟后再试或者自己运行出错请检查自己,o(╥﹏╥)o";
    }
}
3.4.3 目前代码层面存在的问题
  • 每个方法都设置服务降级方法,代码膨胀

    ​ 解决思路:统一的服务降级处理和自定义的服务降级处理分开

    ​ 具体解决:通过@DefaultProperties(defaultFallback = "")解决

    ![](https://gitee.com/honourer/picturebed/raw/master/SpringCloud/图像 (17).png)

    ![](https://gitee.com/honourer/picturebed/raw/master/SpringCloud/图像 (18).png)

    ​ 业务类改造如下【OrderHystrixMain80】

    package com.atguigu.controller;
    
    import com.atguigu.service.PaymentHystrixService;
    import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
    import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
    import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RestController;
    
    import javax.annotation.Resource;
    
    @RestController
    @DefaultProperties(defaultFallback = "paymentInfoTimeoutFallbackMethod")
    public class OrderHystrixController {
        @Resource
        private PaymentHystrixService paymentHystrixService;
    
        @GetMapping("/consumer/payment/hystrix/ok/{id}")
        public String paymentInfo_OK(@PathVariable("id") Integer id){
            return paymentHystrixService.paymentInfo_OK(id);
        }
    
    //    没有@HystrixCommand注解,不进行服务降级
    //    仅有@HystrixCommand,进行服务降级,服务降级方法使用@DefaultProperties统一配置的
    //    有@HystrixCommand注解,同时配置了fallbackMethod属性,进行服务降级,服务降级方法使用fallbackMethod属性指定的
        @GetMapping("/consumer/payment/hystrix/timeout/{id}")
    //    @HystrixCommand(fallbackMethod = "paymentInfoTimeoutFallbackMethod",commandProperties = {
    //            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "1500")
    //    })
        @HystrixCommand
        public String paymentInfo_Timeout(@PathVariable("id") Integer id){
            int age = 10/0;
            return paymentHystrixService.paymentInfo_Timeout(id);
        }
    
        public String paymentInfoTimeoutFallbackMethod(){
            return "我是消费者80,对方支付系统繁忙请10秒钟后再试或者自己运行出错请检查自己,o(╥﹏╥)o";
        }
    }
    

    ​ 与为每个方法配置一个服务降级方法相比,这样处理除了个别重要核心业务有专属的服务降级方法,其它普通的方法可以通过@DefaultProperties(defaultFalback = ")统一跳转到统一处理结果页面,通用的和独享的各自分开,避免了代码膨胀,合理减少了代码量

  • 与业务无关的服务降级方法与业务方法糅合在一起,代码的耦合度高

    解决思路:设置统一的服务降级处理,统一的服务降级不在业务类【Controller】中设置,而在一个单独的类中进行设置

    具体解决:为OpenFeign客户端定义的接口添加一个服务降级处理的实现类

    未来我们要面对的异常:运行时异常、超时异常、宕机

    业务类改造【cloud-consumer-feign-hystrix-order80】

    创建PaymentHystrixService接口的实现类PaymentFallbackService,PaymentHystrixService接口用于进行服务调用,PaymentFallbackService实现类用于进行统一的服务降级处理。

    PaymentFallbackService

    package com.atguigu.service;
    
    import org.springframework.stereotype.Component;
    
    // 配置统一的服务降级处理
    @Component
    public class PaymentFallbackService implements PaymentHystrixService {
    
        // paymentInfo_OK方法的服务降级处理
        @Override
        public String paymentInfo_OK(Integer id) {
            return "Fallback PaymentFallbackService-paymentInfo_OK-o(╥﹏╥)o";
        }
    
        // paymentInfo_Timeout方法的服务降级处理
        @Override
        public String paymentInfo_Timeout(Integer id) {
            return "Fallback PaymentFallbackService-paymentInfo_Timeout-o(╥﹏╥)o";
        }
    }
    

    修改YML,添加如下内容

在OpenFeign中开启Hystrix

feign:
hystrix:
enabled: true


PaymentHystrixService

```java
package com.atguigu.service;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

// @FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT",fallback = PaymentFallbackService.class)
// fallback = PaymentFallbackService.class:配置统一的服务降级处理
@Component
@FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT",fallback = PaymentFallbackService.class)
public interface PaymentHystrixService {

    @GetMapping("/payment/hystrix/ok/{id}")
    public String paymentInfo_OK(@PathVariable("id") Integer id);

    @GetMapping("/payment/hystrix/timeout/{id}")
    public String paymentInfo_Timeout(@PathVariable("id") Integer id);
}

测试

  1. 启动EurekaMain7001

  2. 启动PaymentHystrixMain8001

  3. 启动OrderHystrixMain80

  4. 访问http://localhost/consumer/payment/hystrix/ok/31

    能够正常访问

  5. 关闭PaymentHystrixMain8001,模拟宕机,重新访问http://localhost/consumer/payment/hystrix/ok/31,解耦后的服务降级处理生效。此时服务端provider已经down了,但是我们做了服务降级处理,让客户端在服务端不可用时也会获得提示信息而不会挂起耗死服务器

  • 疑问:虽然按照上述两个问题给出了解决方案,但这两个解决方案能同时用吗?

3.5 服务熔断

断路器:家里保险丝

3.5.1 概述

​ 熔断机制是应对雪崩效应的一种微服务链路保护机制。当扇出链路的某个微服务出错不可用或者响应时间太长时,会进行服务的降级,进而熔断该节点微服务的调用,快速返回错误的响应信息。当检测到该节点微服务调用响应正常后,恢复调用链路。

​ 在Spring Cloud框架里,熔断机制通过Hystrix实现。Hystrix会监控微服务间调用的状况,
​ 当失败的调用到一定阈值,缺省是5秒内20次调用失败,就会启动熔断机制。熔断机制的注解是@HystrixCommand.

3.5.2 案例
  • 修改PaymentService【cloud-provider-hystrix-payment8001】

添加如下内容

//服务熔断
//以下配置的含义
//10次[circuitBreaker.requestVolumeThreshold]请求超过60%的失败率[circuitBreaker.errorThresholdPercentage],也就是6次请求失败就进行熔断,熔断后的10s[circuitBreaker.sleepWindowInMilliseconds]之后进入半开状态,下一个请求是允许通过的,如果请求失败,继续熔断,如果请求成功,断路器不再起效。
@HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
        @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),  //是否开启断路器
        @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),   //请求次数
        @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),  //时间范围【窗口期】
        @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"), //失败率达到多少后跳闸
})
public String paymentCircuitBreaker(@PathVariable("id") Integer id){
    if (id < 0){
        throw new RuntimeException("*****id 不能负数");
    }
    // Hutool工具包的用法参考https://hutool.cn/docs/#/
    String serialNumber = IdUtil.simpleUUID();

    return Thread.currentThread().getName()+"\t"+"调用成功,流水号:"+serialNumber;
}
public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id){
    return "id 不能负数,请稍候再试,(┬_┬)/~~     id: " +id;
}

为什么要配置这些参数,参考官网提供的断路器工作流程

断路器工作流程大致如下:

  1. 判定请求次数是否达到阈值
  2. 判断失败率是否超过阈值
  3. 如果都满足就将断路器的状态由CLOSED置为OPEN,也就是跳闸了
  4. 跳闸时,所有请求都是无效的
  5. 经过设定的窗口期,进入半开状态,允许下次请求通过,请求失败,进入OPEN状态,继续熔断;请求通过,进入CLOSED状态,不再熔断。

配置的参数是从哪来的,参考HystrixCommandProperties类,该类中包含了@HystrixProperty的所有可配置项

  • 修改PaymentController【cloud-provider-hystrix-payment8001】,添加如下方法
//===服务熔断
@GetMapping("/payment/circuit/{id}")
public String paymentCircuitBreaker(@PathVariable("id") Integer id){
    String result = paymentService.paymentCircuitBreaker(id);
    log.info("*******result:"+result);
    return result;
}
  • 测试

    启动EurekaMain7001

    启动PaymentHystrixMain8001

    访问http://localhost:8001/payment/circuit/31,能够正常访问

    多次访问http://localhost:8001/payment/circuit/-31,然后再次访问http://localhost:8001/payment/circuit/31,发现访问失败

    过段时间再次访问http://localhost:8001/payment/circuit/31,发现访问恢复了

3.5.3 总结

熔断状态

打开【Open】:请求不再进行调用当前服务,内部设置时钟一般为MTTR(平均故障处理时间),当打开时长达到所设时钟则进入熔断状态

关闭【Closed】:熔断关闭不会对服务进行熔断

半开【Half Open】:部分请求根据规则调用当前服务,如果请求成功且符合规则则认为当前服务恢复正常,关闭熔断

官方断路器流程图

断路器在什么情况下开始起作用

涉及到断路器的三个重要参数:快照时间窗、请求总数阀值、错误百分比阀值。

  1. 快照时间窗:断路器确定是否打开需要统计- -些请求和错误数据,而统计的时间范围就是快照时间窗,默认为最近的10秒。
  2. 请求总数阀值:在快照时间窗内,必须满足请求总数阀值才有资格熔断。默认为20,意味着在10秒内,如果该hystrix命令的调用次数不足20次,即使所有的请求都超时或其他原因失败,断路器都不会打开。
  3. 错误百分比阀值:当请求总数在快照时间窗内超过了阀值,比如发生了30次调用,如果在这30次调用中,有15次发生了超时异常,也就是超过50%的错误百分比,在默认设定50%阀值情况下,这时候就会将断路器打开。

断路器开启或者关闭的条件

  1. 当满足一定阀值的时候(默认10秒内超过20个请求次数)
  2. 当失败率达到一定的时候(默认10秒内超过50%请求失败)
  3. 到达以上阀值,断路器将会开启
  4. 当开启的时候,所有请求都不会进行转发
  5. 一段时间之后(默认是5秒),这个时候断路器是半开状态,会让其中一个请求进行转发。如果成功,断路器会关闭,若失败,继续开启。重复4和5

断路器打开之后

  1. 再有请求调用的时候,将不会调用主逻辑,而是直接调用降级fallback。通过断路器,实现了自动地发现错误并将降级逻辑切换为主逻辑,减少响应延迟的效果。

  2. 原来的主逻辑要如何恢复呢?

    对于这一问题,hystrix也为我们实现了自动恢复功能。当断路器打开,对主逻辑进行熔断之后, hystrix会启动一 个休眠时间窗,在这个时间窗内,降级逻辑是临时的成为主逻辑,当休眠时间窗到期,断路器将进入半开状态,释放-次请求到原来的主逻辑 上,如果此次请求正常返回,那么断路器将继续闭合,主逻辑恢复,如果这次请求依然有问题,断路器继续进入打开状态,休眠时间窗重新计时。

HystrixCommandProperties中所有的配置

3.6 服务限流

后面高级篇讲解alibaba的Sentinel说明

4. Hystrix工作流程

参考网站:https://github.com/Netflix/Hystrix/wiki/How-it-Works

依据图中哪些情况下会触发服务降级?

  1. 断路器打开状态
  2. 信号量/线程池满了
  3. Hystrix[Observable]Command的construct()/run()方法执行失败

5. 服务监控HystrixDashboard

5.1 是什么

​ 除了隔离依赖服务的调用以外,Hystrix还提供了准实时的调用监控(Hystrix Dashboard) ,Hystrix会持续地记录所有通过Hystrix发起的请求的执行信息,并以统计报表和图形的形式展示给用户,包括每秒执行多少请求多少成功,多少失败等。Netflix通过hystrix-metrics-event-stream项目实现了对以上指标的监控。Spring Cloud也提供了Hystrix Dashboard的整合,对监控内容转化成可视化界面。

​ 用于监控微服务提供者,能够查看微服务提供者提供的服务被调用的情况

5.2 搭建监控测试平台

  1. 建Module【cloud-consumer-hystrix-dashboard9001】

  2. 改POM

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <parent>
            <artifactId>cloud2020</artifactId>
            <groupId>com.atguigu.springcloud</groupId>
            <version>1.0-SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>
    
        <artifactId>cloud-consumer-hystrix-dashboard9001</artifactId>
    
        <dependencies>
            <!--新增Hystrix dashboard-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</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>
    
    </project>
    
  3. 写YML

    server:
      port: 9001
    
  4. 主启动

    package com.atguigu.springcloud;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
    
    // 开启HystrixDashboard
    @EnableHystrixDashboard
    @SpringBootApplication
    public class HystrixDashboardMain9001 {
        public static void main(String[] args) {
            SpringApplication.run(HystrixDashboardMain9001.class, args);
        }
    }
    
  5. 测试

    启动cloud-consumer-hystrix-dashboard9001

    访问http://localhost:9001/hystrix,看到如下界面表示服务监控搭建成功

5.3 使用HystrixDashboard监控服务提供者

  1. 修改cloud-provider-hystrix-payment8001

    ​ 所有需要被9001监控的微服务提供者(8001/8002/8003)都需要在POM中添加监控依赖配置

    <!-- actuator监控信息完善-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    

    ​ 在主启动类中指定监控路径

    package com.atguigu.springcloud;
    
    import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.web.servlet.ServletRegistrationBean;
    import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
    import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
    import org.springframework.context.annotation.Bean;
    
    //@EnableCircuitBreaker:主启动类激活服务降级
    @SpringBootApplication
    @EnableEurekaClient
    @EnableCircuitBreaker
    public class PaymentHystrixMain8001 {
        public static void main(String[] args) {
            SpringApplication.run(PaymentHystrixMain8001.class, args);
        }
    
        /**
         * 此配置是为了服务监控而配置, 与服务容错本身无关, springcloud升级后的坑
         * ServletRegistrationBean因为springboot的默认路径不是"/hystrix.stream",
         * 只要在自己己的项目里配置上下面的servlet就可以了
         * @return
         */
        @Bean
        public ServletRegistrationBean getServlet(){
            HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
            ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
            registrationBean.setLoadOnStartup(1);
            registrationBean.addUrlMappings("/hystrix.stream");
            registrationBean.setName("HystrixMetricsStreamServlet");
            return registrationBean;
        }
    }
    
  2. 监控测试

    启动HystrixDashboardMain9001

    启动EurekaMain7001

    启动PaymentHystrixMain8001

    访问http://localhost:9001/hystrix并填写监控地址http://localhost:8001/hystrix.stream

    不断访问8001的两个服务http://localhost:8001/payment/circuit/31,http://localhost:8001/payment/circuit/-31,能够看到监控信息的变化

  3. 监控仪表盘详解

    7色

    1圈

    ​ 实心圆:共有两种含义。它通过颜色的变化代表了实例的健康程度,它的健康度从绿色<黄色<橙色<红色递减。该实心圆除了颜色的变化之外,它的大小也会根据实例的请求流量发生变化,流量越大该实心圆就越大。所以通过该实心圆的展示,就可以在大量的实例中快速的发现故障实例和高压力实例。

    1线

    ​ 曲线:用来记录2分钟内流量的相对变化,可以通过它来观察到流量的上升和下降趋势。

    完整说明

  4. 局限性

    ​ 需要我们自己搭建服务监控平台,高级篇讲解alibaba的Sentinel会直接提供给我们一个监控平台,相比Hystrix要更好一点

标签:服务,降级,系列,hystrix,SpringCloud,springframework,import,org,id
From: https://www.cnblogs.com/wzzzj/p/18039253

相关文章

  • SpringCloud系列之(六)服务调用
    服务调用完成微服务之间的分布式调用一、Ribbon1.概述1.1是什么​ SpringCloudRibbon是基于NetflixRibbon实现的一套客户端负载均衡【消费者侧80】的工具。​ 简单的说,Ribbon是Netflix发布的开源项目,主要功能是提供客户端的软件负载均衡算法和服务调用。Ribbon客户端组......
  • SpringCloud系列之(五)服务注册中心
    服务注册中心【服务注册与发现】一、EurekaSpring社区出的,Nacos是阿里出的1.Eureka基础知识1.1什么是服务治理?​ SpringCloud封装了Netflix公司开发的Eureka模块来实现服务治理。​ 在传统的rpc远程调用框架中,服务与服务之间依赖关系比较复杂,管理比较复杂,所以需要......
  • SpringCloud系列之(四)微服务架构编码构建
    微服务架构编码构建一、IDEA新建project工作空间1.微服务cloud整体聚合父工程Project【父工程Project空间新建】NewProject聚合总工程名字Maven选版本字符编码注解生效激活java编译版本选8FileType过滤【选做】删除src目录2.父工程POM文......
  • SpringCloud系列之(二)从2 2 x和H版开始说起
    从2.2.x和H版开始说起SpringCloudDalston.SR1+SpringBoot1.5.9版本的搭配已过时一、SpringBoot版本选择SpringBoot是以数字作为版本的,如:SpringBoot1.5.9二、SpringCloud版本选择SpringCloud的版本命名规则及版本关系​ SpringCloud采用了英国伦敦地铁站的名称来命名,......
  • SpringCloud系列之(一)微服务架构零基础理论入门
    微服务架构零基础理论入门一、微服务架构概述1.什么是微服务由MartinFlower提出微小的、独立的进程、轻量级、可独立部署​ 微服务架构是种架构模式,它提倡将单一应用程序划分成一组小的服务,服务之间互相协调、互相配合,为用户提供最终价值。每个服务运行在其独立的进程中,......
  • SpringBoot 2x 系列之(七)web场景
    web场景1.SpringMVC自动配置概览SpringBootprovidesauto-configurationforSpringMVCthatworkswellwithmostapplications.(大多场景我们都无需自定义配置)Theauto-configurationaddsthefollowingfeaturesontopofSpring’sdefaults:InclusionofCont......
  • SpringBoot 2x 系列之(五)开发技巧
    开发技巧1.Lombok1.应用场景简化JavaBean的开发帮我们在编译时生成get、set、toString方法2.安装及使用引入依赖【SpringBoot已经做了版本仲裁】<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></depende......
  • SpringBoot 2x 系列之(四)自动配置
    自动配置1.引导加载自动配置类见SpringBoot1.md一、SpringBoot入门4.2主程序类,主入口类【自动配置原理】1.1@SpringBootConfiguration见SpringBoot1.md一、SpringBoot入门4.2主程序类,主入口类【自动配置原理】[email protected]@AutoConfi......
  • SpringBoot 2x 系列之(三)容器功能
    容器功能1.组件添加1.1@Configuration结合@Bean注册组件@Configuration见[email protected]@Component、@Controller、@Service、@Repository见Spring.md相关内容1.3@ComponentScan见[email protected]@Import见Spring.md8.......
  • SpringBoot 2x 系列之(二)SpringBoot特点
    SpringBoot特点1.依赖管理特性SpringBoot已经为我们做了版本仲裁,那么如果我们要修改已经做了版本仲裁的依赖,比如mysql驱动的依赖,该怎么做呢?查看spring-boot-dependencies里面规定的当前依赖版本用的properties属性在当前项目里面重新配置<properties><mysql.versi......