三、服务降级、服务熔断 和 服务限流


一、Hystrix 断路器


1. 分布式系统面临的问题

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

1.1 服务雪崩
  • 多个微服务之间调用的时候,假设 微服务A 调用 微服务B 和 微服务C,微服务B 和 微服务C 又调用其它的微服务,这就是所谓的 “扇出”。
  1. 如果扇出的链路上某个微服务的调用响应时间过长 或者 不可用,对 微服务A 的调用就会占用越来越多的系统资源,进而引起系统崩溃,所谓的 “雪崩效应”。

  • 对于高流量的应用来说,单一的后端依赖可能会导致所有服务器上的所有资源都在几秒钟内饱和。
  1. 比失败更糟糕的是,这些应用程序还可能导致服务之间的延迟增加,备份队列,线程和其他系统资源紧张,导致整个系统发生更多的级联故障。
  2. 这些都表示需要对 故障 和 延迟 进行隔离和管理,以便单个依赖关系的失败,不能取消整个应用程序或系统。

  • 所以,通常当你发现一个模块下的某个实例失败后,这时候这个模块依然还会接收流量,然后这个有问题的模块还调用了其他的模块,这样就会发生级联故障,或者叫 雪崩

2. 是什么

  • Hystrix 是一个用于处理分布式系统的 延迟容错 的开源库。
  1. 在分布式系统里,许多依赖不可避免的会调用失败,比如:超时、异常 等。
  2. Hystrix 能够保证在一个依赖出问题的情况下,不会导致整体服务失败,避免级联故障,以提高分布式系统的弹性

  • “断路器” 本身是一种开关装置。
  1. 当某个服务单元发生故障之后,通过断路器的故障监控(类似熔断保险丝),向调用方返回一个符合预期的、可处理的备选响应(Fallback)
  2. 而不是长时间的等待 或者 抛出调用方无法处理的异常,这样就保证了服务调用方的线程不会被长时间、不必要地占用,从而避免了故障在分布式系统中的蔓延,乃至 雪崩

3. 能干嘛


3.1 服务降级(Fallback
  • 服务器忙,请稍后再试,不让客户端等待并立刻返回一个友好提示 Fallback。

  • 哪些情况会出发降级。
  1. 程序运行异常。
  2. 超时。
  3. 服务熔断触发服务降级。
  4. 线程池/信号量打满也会导致服务降级。

3.2 服务熔断(@HystrixCommand
  • 类比 保险丝 达到最大服务访问后,直接拒绝访问。
    拉闸限电,然后调用 服务降级 的方法并返回友好提示。

  • 就像保险丝。
    服务的降级 > 进而熔断 > 恢复调用链路。

  • 熔断机制概述。
  1. 熔断机制 是应对 雪崩效应 的一种微服务链路保护机制。
    当扇出链路的某个微服务 出错不可用 或者 响应时间太长 时,会进行服务的降级,进而 熔断该节点微服务的调用,快速返回错误的响应信息。
  2. 当检测到该节点微服务调用响应正常后,恢复调用链路
  3. 在 Spring Cloud 框架里,熔断机制 通过 Hystrix 实现。
    Hystrix 会监控微服务间调用的状况,当失败的调用到一定阈值,缺省是 5 秒内 20 次调用失败,就会启动 熔断机制,熔断机制 的注解是 @HystrixCommand

  • 熔断类型。
  1. 熔断打开。
    请求不再进行调用当前服务,内部设置时钟一般为 MTTR(平均故障处理时间),当打开时长达到所设时钟则进入 半熔断状态
  2. 熔断关闭。
    熔断关闭不会对服务进行熔断。
  3. 熔断半开。
    部分请求根据规则调用当前服务,如果请求成功且符合规则则认为当前服务恢复正常,关闭熔断。

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

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

  • 断路器打开之后。
  1. 再有请求调用的时候,将不会调用主逻辑,而是直接调用 降级 Fallback
    通过断路器,实现了自动地发现错误,并将降级逻辑切换为主逻辑,减少响应延迟的效果。
  2. 原来的主逻辑要如何恢复呢?
    对于这一问题,Hystrix 也为我们实现了自动恢复功能。
  1. 当断路器打开,对主逻辑进行 熔断 之后,Hystrix 会启动一个休眠时间窗,在这个时间窗内,降级逻辑 是临时的成为 主逻辑。
  2. 当休眠时间窗到期,断路器将进入 半开状态,释放一次请求到原来的主逻辑上。
  3. 如果此次请求正常返回,那么断路器将继续 闭合状态,主逻辑恢复。
  4. 如果这次请求依然有问题,断路器继续进入打开状态,休眠时间窗重新计时。
// All配置
@HystrixCommand(
	fallbackMethod = "str_fallbackMethod",
	groupKey = "strGroupCommand",
	commandKey = "strCommand",
	threadPoolKey = "strThreadPool",
	commandProperties = {
		// 设置隔离策略,THREAD 表示线程池 SEMAPHORE:信号池隔离
		@HystrixProperty(name = "execution.isolation.strategy", value = "THREAD"),
		// 当隔离策略选择信号池隔离的时候,用来设置信号池的大小(最大并发数)
		@HystrixProperty(name = "execution.isolation.semaphore.maxConcurrentRequests", value = "10"),
		// 配置命令执行的超时时间
		@HystrixProperty(name = "execution.isolation.thread.timeoutinMilliseconds", value = "10"),
		// 是否启用超时时间
		@HystrixProperty(name = "execution.timeout.enabled", value = "true"),
		// 执行超时的时候是否中断
		@HystrixProperty(name = "execution.isolation.thread.interruptOnTimeout", value = "true"),
		// 执行被取消的时候是否中断
		@HystrixProperty(name = "execution.isolation.thread.interruptOnCancel", value = "true"),
		// 允许回调方法执行的最大并发数
		@HystrixProperty(name = "fallback.isolation.semaphore.maxConcurrentRequests", value = "10"),
		// 服务降级是否启用,是否执行回调函数
		@HystrixProperty(name = "fallback.enabled", value = "true"),
		// 是否启用断路器
		@HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
		// 该属性用来设置在滚动时间窗中,断路器熔断的最小请求数。例如,默认该值为 20 的时候,
		// 如果滚动时间窗(默认10秒)内仅收到了19个请求, 即使这19个请求都失败了,断路器也不会打开。
		@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "20"),
		// 该属性用来设置在滚动时间窗中,表示在滚动时间窗中,在请求数量超过
		// circuitBreaker.requestVolumeThreshold 的情况下,如果错误请求数的百分比超过50,
		// 就把断路器设置为 "打开" 状态,否则就设置为 "关闭" 状态。
		@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50"),
		// 该属性用来设置当断路器打开之后的休眠时间窗。 休眠时间窗结束之后,
		// 会将断路器置为 "半开" 状态,尝试熔断的请求命令,如果依然失败就将断路器继续设置为 "打开" 状态,
		// 如果成功就设置为 "关闭" 状态。
		@HystrixProperty(name = "circuitBreaker.sleepWindowinMilliseconds", value = "5000"),
		// 断路器强制打开
		@HystrixProperty(name = "circuitBreaker.forceOpen", value = "false"),
		// 断路器强制关闭
		@HystrixProperty(name = "circuitBreaker.forceClosed", value = "false"),
		// 滚动时间窗设置,该时间用于断路器判断健康度时需要收集信息的持续时间
		@HystrixProperty(name = "metrics.rollingStats.timeinMilliseconds", value = "10000"),
		// 该属性用来设置滚动时间窗统计指标信息时划分"桶"的数量,断路器在收集指标信息的时候会根据
		// 设置的时间窗长度拆分成多个 "桶" 来累计各度量值,每个"桶"记录了一段时间内的采集指标。
		// 比如 10 秒内拆分成 10 个"桶"收集这样,所以 timeinMilliseconds 必须能被 numBuckets 整除。否则会抛异常
		@HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "10"),
		// 该属性用来设置对命令执行的延迟是否使用百分位数来跟踪和计算。如果设置为 false, 那么所有的概要统计都将返回 -1。
		@HystrixProperty(name = "metrics.rollingPercentile.enabled", value = "false"),
		// 该属性用来设置百分位统计的滚动窗口的持续时间,单位为毫秒。
		@HystrixProperty(name = "metrics.rollingPercentile.timeInMilliseconds", value = "60000"),
		// 该属性用来设置百分位统计滚动窗口中使用 “ 桶 ”的数量。
		@HystrixProperty(name = "metrics.rollingPercentile.numBuckets", value = "60000"),
		// 该属性用来设置在执行过程中每个 “桶” 中保留的最大执行次数。如果在滚动时间窗内发生超过该设定值的执行次数,
		// 就从最初的位置开始重写。例如,将该值设置为100, 滚动窗口为10秒,若在10秒内一个 “桶 ”中发生了500次执行,
		// 那么该 “桶” 中只保留 最后的100次执行的统计。另外,增加该值的大小将会增加内存量的消耗,并增加排序百分位数所需的计算时间。
		@HystrixProperty(name = "metrics.rollingPercentile.bucketSize", value = "100"),
		// 该属性用来设置采集影响断路器状态的健康快照(请求的成功、 错误百分比)的间隔等待时间。
		@HystrixProperty(name = "metrics.healthSnapshot.intervalinMilliseconds", value = "500"),
		// 是否开启请求缓存
		@HystrixProperty(name = "requestCache.enabled", value = "true"),
		// HystrixCommand的执行和事件是否打印日志到 HystrixRequestLog 中
		@HystrixProperty(name = "requestLog.enabled", value = "true"),
	},
	threadPoolProperties = {
		// 该参数用来设置执行命令线程池的核心线程数,该值也就是命令执行的最大并发量
		@HystrixProperty(name = "coreSize", value = "10"),
		// 该参数用来设置线程池的最大队列大小。当设置为 -1 时,线程池将使用 SynchronousQueue 实现的队列,
		// 否则将使用 LinkedBlockingQueue 实现的队列。
		@HystrixProperty(name = "maxQueueSize", value = "-1"),
		// 该参数用来为队列设置拒绝阈值。 通过该参数, 即使队列没有达到最大值也能拒绝请求。
		// 该参数主要是对 LinkedBlockingQueue 队列的补充,因为 LinkedBlockingQueue
		// 队列不能动态修改它的对象大小,而通过该属性就可以调整拒绝请求的队列大小了。
		@HystrixProperty(name = "queueSizeRejectionThreshold", value = "5"),
	}
)
public String strConsumer() {
    return "hello 2020";
}
public String str_fallbackMethod() {
    return "*****fall back str_fallbackMethod";
}

3.3 服务限流
  • 秒杀高并发等操作,严禁一窝蜂的过来拥挤,大家排队,一秒钟 N 个,有序进行。

4. Hystrix 案例


4.1 新建 Module cloud-provider-payment-hystrix8001

4.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>cloud-2020</artifactId>
        <groupId>com.qs.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-provider-payment-hystrix8001</artifactId>

    <dependencies>
        <!--hystrix-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
        <!--eureka-client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

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

        <!--自定义API通用包-->
        <dependency>
            <groupId>com.qs.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>${project.version}</version>
        </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>

4.3 YML
server:
  port: 8001

spring:
  application:
    name: provider-payment-service

eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka

4.4 主启动
  • @EnableCircuitBreaker
@SpringBootApplication
// 启用EurekaClient,会自动注册到 EurekaServer中
@EnableEurekaClient
// 对Hystrix降级熔断机制的支持
@EnableCircuitBreaker
public class PaymentHystrixMain8001 {

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

    /**
     * 此配置是为了服务监控而配置,与服务容错本身无关,SpringCloud 升级后的坑,
     * ServletRegistrationBean 因为 SpringBoot的默认路径不是"/hystrix.stream",
     * 只要在自己的项目里配置上下面的servlet就可以了
     */
    @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;
    }
}

4.5 新建 PaymentService【服务降级、服务熔断】

@HystrixCommand
@HystrixProperty

@Service
public class PaymentService {

    /**
     * 正常访问,一切OK
     *
     * @param id
     * @return
     */
    public String ok(Integer id) {
        return "线程:" + Thread.currentThread().getName() + ",ok,id:" + id;
    }


    /**
     * 服务降级
     * 请求`5`秒超时,服务被降级,调用`timeout_Handler`方法
     */
    @HystrixCommand(fallbackMethod = "timeout_Handler", commandProperties = {
            // 我们能接受3秒钟,它运行5秒钟,超时异常
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
    })
    public String timeout(Integer id) {
        // 1. 程序异常
//        int age = 10 / 0;
        int timeout = 5;
        try {
            // 2. 程序超时
            TimeUnit.SECONDS.sleep(timeout);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程:" + Thread.currentThread().getName() + ",timeout,id:" + id + ",耗费秒:" + timeout;
    }

    /**
     * 服务降级处理
     *
     * @param id
     * @return
     */
    public String timeout_Handler(Integer id) {
        return "线程:" + Thread.currentThread().getName() + ",timeout_Handler,id:" + id;
    }


    /**
     * 服务熔断
     * 在 10秒范围内请求 10次,失败率达到 60后跳闸熔断,开启断路器;
     * 服务熔断后,一定时间后重新恢复,关闭断路器
     */
    @HystrixCommand(fallbackMethod = "circuitBreaker_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 circuitBreaker(Integer id) {
        if (id < 0) {
            throw new RuntimeException("失败率达到60%后,服务熔断,id不能负数");
        }
        String serialNumber = IdUtil.simpleUUID();
        return Thread.currentThread().getName() + "\t" + "调用成功," + serialNumber;
    }

	/**
     * 服务熔断处理
     *
     * @param id
     * @return
     */
    public String circuitBreaker_Fallback(Integer id) {
        return "id不能负数,请稍后再试,id:" + id;
    }
}

4.6 新建 PaymentController
@RestController
@RequestMapping("payment")
@Slf4j
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @GetMapping("ok/{id}")
    public String ok(@PathVariable("id") Integer id) {
        String result = paymentService.ok(id);
        log.info("result:" + result);
        return result;
    }

    /**
     * 服务降级
     *
     * @param id
     * @return
     */
    @GetMapping("timeOut/{id}")
    public String timeOut(@PathVariable("id") Integer id) {
        String result = paymentService.timeOut(id);
        log.info("result:" + result);
        return result;
    }

    /**
     * 服务熔断
     *
     * @param id
     * @return
     */
    @GetMapping("circuitBreaker/{id}")
    public String circuitBreaker(@PathVariable("id") Integer id) {
        String result = paymentService.circuitBreaker(id);
        log.info("paymentCircuitBreaker:" + result);
        return result;
    }
}

4.7 服务降级测试

http://localhost:8001/payment/timeout/1
http://localhost:8001/payment/ok/1


4.8 服务熔断测试

正确 > 错误10次 > 降级熔断 > 恢复
http://localhost:8001/payment/circuitBreaker/-1 请求10次熔断
http://localhost:8001/payment/circuitBreaker/1 恢复
http://localhost:8001/payment/ok/1


4.9 JMeter 压测测试
  • 为什么会被卡死。
    因为 Tomcat 的默认的工作线程数被打满了,没有多余的线程来分担压力和处理。

4.10 新建 Module cloud-consumer-order-feign-hystrix80

4.11 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>cloud-2020</artifactId>
        <groupId>com.qs.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-consumer-order-feign-hystrix80</artifactId>

    <dependencies>
        <!--hystrix-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
        <!--eureka-client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!--openfeign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

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

        <!--自定义API通用包-->
        <dependency>
            <groupId>com.qs.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>${project.version}</version>
        </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>

4.12 YML
server:
  port: 80

eureka:
  client:
    register-with-eureka: false
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/

## 用于服务降级接口处理,在注解 @FeignClient中添加 fallbackFactory属性值
# 在 Feign中开启 Hystrix
feign:
  hystrix:
    enabled: true

4.13 主启动
  • @EnableHystrix
@SpringBootApplication
@EnableFeignClients
@EnableHystrix
public class OrderHystrixMain80 {

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


4.14 新建 PaymentHystrixService
@Component
// 为接口所有方法统一进行异常处理
@FeignClient(value = "PROVIDER-PAYMENT-SERVICE", fallback = PaymentHystrixServiceFallback.class)
public interface PaymentHystrixService {

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

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

}

4.15 新建 PaymentHystrixServiceFallback
@Component
public class PaymentHystrixServiceFallback implements PaymentHystrixService {

    @Override
    public String ok(Integer id) {
        return "ok_Fallback";
    }

    @Override
    public String timeout(Integer id) {
        return "timeout_Fallback";
    }
}

4.15 新建 OrderHystirxController【指定处理、全局处理、接口处理】
  • 指定处理:@HystrixCommand。
  • 全局处理:@DefaultProperties。
  • 接口处理:@FeignClient。
@RestController
@RequestMapping("order")
@Slf4j
// 配置全局处理
@DefaultProperties(defaultFallback = "global_Fallback")
public class OrderHystirxController {

    @Resource
    private PaymentHystrixService paymentHystrixService;

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


    @GetMapping("timeout/{id}")
    @HystrixCommand(fallbackMethod = "timeout_Fallback", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1500")
    })
    public String timeout(@PathVariable("id") Integer id) {
        return paymentHystrixService.timeout(id);
    }

    /**
     * 指定处理
     *
     * @param id
     * @return
     */
    public String timeout_Fallback(@PathVariable("id") Integer id) {
        return "timeout_Fallback异常处理信息,请稍后再试~~,id:" + id;
    }


    @GetMapping("timeout2/{id}")
    // 加@DefaultProperties注解,并且没有写具体方法名字,就用统一全局的
    @HystrixCommand
    public String timeout2(@PathVariable("id") Integer id) {
        return paymentHystrixService.timeout(id);
    }

    /**
     * 全局处理
     *
     * @return
     */
    public String global_Fallback() {
        return "global_Fallback异常处理信息,请稍后再试~~";
    }
}

4.16 测试

http://localhost/order/timeout/1
http://localhost/order/timeout2/1
http://localhost/order/ok/1


5. Hystrix 工作流程

在这里插入图片描述

  1. 创建 HystrixCommand(用在依赖的服务返回单个操作结果的时候) 或 HystrixObserableCommand(用在依赖的服务返回多个操作结果的时候) 对象。

  1. 命令执行。
    其中 HystrixComand 实现了下面前两种执行方式。
    而 HystrixObservableCommand 实现了后两种执行方式。
  1. execute():同步执行,从依赖的服务返回一个单一的结果对象, 或是在发生错误的时候抛出异常。
  2. queue():异步执行, 直接返回 一个Future 对象, 其中包含了服务执行结束时要返回的单一结果对象。
  3. observe():返回 Observable 对象,它代表了操作的多个结果,它是一个 Hot Obserable(不论 “事件源” 是否有 “订阅者”,都会在创建后对事件进行发布,所以对于 Hot Observable 的每一个 “订阅者” 都有可能是从 “事件源” 的中途开始的,并可能只是看到了整个操作的局部过程)。
  4. toObservable(): 同样会返回 Observable 对象,也代表了操作的多个结果,但它返回的是一个 Cold Observable(没有 “订阅者” 的时候并不会发布事件,而是进行等待,直到有 “订阅者” 之后才发布事件,所以对于 Cold Observable 的订阅者,它可以保证从一开始看到整个操作的全部过程)。

  1. 若当前命令的 请求缓存功能 是被启用的, 并且该命令缓存命中, 那么缓存的结果会立即以 Observable 对象的形式返回。

  1. 检查 断路器 是否为打开状态。
    如果断路器是打开的,那么 Hystrix 不会执行命令,而是转接到 Fallback 处理逻辑(第 8 步)。
    如果断路器是关闭的,检查是否有可用资源来执行命令(第 5 步)。

  1. 线程池/请求队列/信号量是否占满。
    如果命令依赖服务的 专有线程池 和 请求队列,或者 信号量(不使用线程池的时候)已经被占满, 那么 Hystrix 也不会执行命令, 而是转接到 Fallback 处理逻辑(第 8 步)。

  1. Hystrix 会根据我们编写的方法来决定采取什么样的方式去请求依赖服务。
    HystrixCommand.run() :返回一个单一的结果,或者抛出异常
    HystrixObservableCommand.construct(): 返回一个 Observable 对象来发射多个结果,或通过 onError 发送错误通知。

  1. Hystrix 会将 “成功”、“失败”、“拒绝”、“超时” 等信息报告给断路器,而断路器会维护一组计数器来统计这些数据。
    断路器会使用这些统计数据来决定是否要将断路器打开,来对某个依赖服务的请求进行 “熔断/短路”。

  1. 当命令执行失败的时候, Hystrix 会进入 Fallback 尝试回退处理, 我们通常也称该操作为 “服务降级”。
    而能够引起 服务降级 处理的情况有下面几种。
  1. 第 4 步:当前命令处于 “熔断/短路” 状态,断路器是打开的时候。
  2. 第 5 步:当前命令的 线程池、 请求队列 或者 信号量 被占满的时候。
  3. 第 6 步:HystrixObservableCommand.construct() 或 HystrixCommand.run() 抛出异常的时候。

  1. 当 Hystrix 命令执行成功之后, 它会将处理结果直接返回 或 是以 Observable 的形式返回。

  • Tips:如果我们没有为命令实现 降级逻辑 或者 在降级处理逻辑中抛出了异常。
  1. Hystrix 依然会返回一个 Observable 对象, 但是它不会发射任何结果数据, 而是通过 onError 方法通知命令立即中断请求,并通过 onError() 方法将引起命令失败的异常发送给调用者。

6. HystrixDashboard 服务监控

  • 除了 隔离 依赖服务 的调用以外,Hystrix 还提供了 准实时的调用监控(Hystrix Dashboard)
  1. Hystrix 会持续地记录所有通过 Hystrix 发起的请求的执行信息,并以统计报表和图形的形式展示给用户,包括每秒执行多少请求多少成功,多少失败等。
  2. Netflix 通过 hystrix-metrics-event-stream 项目实现了对以上指标的监控。
  3. Spring Cloud 也提供了 Hystrix Dashboard 的整合,对监控内容转化成可视化界面。
    在这里插入图片描述
    在这里插入图片描述
  • 实心圆:共有两种含义。
  1. 它通过颜色的变化代表了实例的健康程度,它的健康度从 绿色 < 黄色 < 橙色 < 红色 递减。
  2. 该实心圆除了颜色的变化之外,它的大小也会根据实例的请求流量发生变化,流量越大该实心圆就越大。
  3. 所以通过该实心圆的展示,就可以在大量的实例中,快速的发现 故障实例 和 高压力实例。
  • 曲线:用来记录 2 分钟内流量的相对变化。
    可以通过它来观察到 流量的 上升 和 下降 趋势。

7. HystrixDashboard 案例


7.1 新建 Module cloud-consumer-hystrix-dashboard9001

7.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>cloud-2020</artifactId>
        <groupId>com.qs.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>

        <!--actuator-->
        <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>

7.3 YML
server:
  port: 9001

7.4 主启动
@SpringBootApplication
@EnableHystrixDashboard
public class HystrixDashboardMain9001 {

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

}

7.5 访问

http://localhost:9001/hystrix
在这里插入图片描述

  1. Delay:该参数用来控制服务器上 轮询监控信息 的延迟时间(默认为 2000 毫秒)。
    可以通过配置该属性来降低客户端的 网络 和 CPU 消耗。
  2. Title:该参数对应了头部标题 Hystrix Stream 之后的内容(默认会使用具体监控实例的URL),可以通过配置该信息来展示更合适的标题。

  • 成功。
    在这里插入图片描述

  • 失败。
    在这里插入图片描述

  • 整图说明。
    在这里插入图片描述

  • 整图说明二。
    在这里插入图片描述
  • 实心圆:共有两种含义。
  1. 它通过颜色的变化代表了实例的健康程度,它的健康度从绿色 < 黄色 < 橙色 < 红色递减。
  • 该实心圆除了颜色的变化之外,它的大小也会根据实例的请求流量发生变化,流量越大该实心圆就越大。
  1. 所以通过该实心圆的展示,就可以在大量的实例中快速的发现 故障实例 和 高压力实例
  • 曲线:用来记录 2 分钟内流量的相对变化,可以通过它来观察到流量的上升和下降趋势。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

骑士梦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值