9.Cloud Hystrix熔断器

1、概述

1.1、分布式系统面临的问题

  复杂分布式体系结构中的应用程序有数十个依赖关系,每个依赖关系在某些时候将不可避免地失败。这就造成有可能会发生服务雪崩。那么什么是服务雪崩呢?

  多个微服务之间调用的时候,假设微服务A调用微服务B和微服务C,微服务B和微服务C又调用其他的微服务,这就是所谓的“扇出”(向一把打开的折扇)。如果扇出的链路上某个微服务的调用响应时间过长或者不可用,对微服务A的调用就会占用越来越多的系统资源,进而引起系统崩溃,这就是所谓的”雪崩效应“。也就是系统的 高可用 受到了破坏。

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

  所以,通常当发现一个模块下的某个实例失败后,这时候这个模块依然还会接受流量,然后这个有问题的模块还调用了其他的模块,这样就会发生级联故障,或者叫做雪崩。而面对这种糟糕的问题,我们就应该采取 服务降级、服务熔断 等方式来解决。

1.2、Hystrix是什么

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

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

1.3、Hystrix能做什么?
  主要有服务降级、服务熔断、接近实时的监控、限流、隔离等等,其官方文档参考。当然Hystrix现在已经停更了,虽然有一些替代品,但是学习Hystrix及其里面的思想还是非常重要的!

2、Hystrix重要概念

2.1、服务降级——Fall Back

  假设微服务A要调用的服务B不可用了,需要服务B提供一个兜底的解决方法,而不是让服务A在那里傻等,耗死。不让客户端等待并立刻返回一个友好图示,比如像客户端提示服务器忙,请稍后再试等。哪些情况会触发服务降级呢?

  比如程序运行异常、超时、服务熔断触发服务降级、线程池/信号量打满也会导致服务降级。

2.2、服务熔断——Break

  服务熔断就相当于物理上的熔断保险丝。类比保险丝达到最大服务访问后,直接拒绝访问,拉闸断点,然后调用服务降级的方法并返回友好提示。

2.3、服务限流——Flow Limit

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

3、Hystrix案例实操

3.1、构建

  新建一个Module:cloud-provider-hystrix-payment8001作为服务提供方的微服务,和之前的服务消费方同样选择8001端口,但是在POM文件中需要引入Hystrix的依赖:

<?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>
        <!--eureka client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <dependency>
            <groupId>com.atguigu.springcloud</groupId>
            <artifactId>cloud-api-common</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>

  然后编写其配置文件,端口号为8001,服务名为cloud-provider-hystrix-payment,以使其入驻服务注册中心。

server:
  port: 8001
spring:
  application:
    name: cloud-provider-hystrix-payment
eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka

  然后编写其主启动类

package com.atguigu.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

/**
 * @create 2021-02-05 13:11
 */
@SpringBootApplication
@EnableEurekaClient
public class PaymentHystrixMain8001 {
    public static void main(String[] args) {
        SpringApplication.run(PaymentHystrixMain8001.class, args);
    }
}

  之后编写其业务类,service编写如下:

package com.atguigu.springcloud.service;

import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @create 2021-02-05 13:20
 */
@Service
public class PaymentService {

    /**
     * 正常访问
     * @param id
     * @return
     */
    public String paymentInfo_OK(Long id) {
        return "线程池: " + Thread.currentThread().getName() + " paymentInfo_OK, id: " + id;
    }

    /**
     * 模拟复杂业务需要3秒钟
     * @param id
     * @return
     */
    public String paymentInfo_TimeOut(Long id) {
        int time = 3;
        //暂停几秒钟线程,程序本身没有错误,就是模拟超时
        try {
            TimeUnit.SECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池: " + Thread.currentThread().getName() + " paymentInfo_TimeOut, id: " + id;
    }

}

  Controller编写入下:

package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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;

/**
 * @create 2021-02-05 13:26
 */
@RestController
@Slf4j
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

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

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

    @GetMapping("/payment/hystrix/timeout/{id}")
    public String paymentInfo_TimeOut(@PathVariable("id") Long id) {
        String result = paymentService.paymentInfo_TimeOut(id);
        log.info("========result:" + result);
        return result;
    }
}

  也就是说cloud-provider-hystrix-payment服务提供了两个方法,paymentInfo_OK 方法可以很快访问,paymentInfo_TimeOut 方法我们模拟了一个复杂的业物逻辑,通过线程休眠的方式使其模拟一个需要执行3秒的服务方法。

  在启动了注册中心和8001服务后,我们对服务的 paymentInfo_OK(下面用OK代替) 和 paymentInfo_TimeOut (下面用TO代替)分别进行访问,我们发现,http://localhost:8001/payment/hystrix/ok/31 可以很快的访问,而http://localhost:8001/payment/hystrix/timeout/31 每次访问大约需要3秒的时间。

3.2、高并发测试

  3.2.1、服务提供方自测压力测试:

  需要3秒的复杂业务逻辑 TO 访问时,需要时间很少的 OK 是完全可以正常访问的,但是在高并发的情况下,也就是说 TO 有很多访问量的时候,OK 还能够这么正常的访问吗?下面我们用 Jmeter 进行高并发压力测试,用20000个请求都去访问 TO 服务,在 Jmeter 中新建一个线程组:测试Hystrix用来模拟高并发访问 TO服务,线程组配置参数如下:
在这里插入图片描述
  然后我们用该线程组发送HTTP请求给 TO 服务,创建如下的HTTP请求进行压力测试:
在这里插入图片描述
  而此时我们再去访问 OK 服务时什么样的呢??

  测试结果:

  OK 服务无妨像之前一样很快能够得到访问,这里我们模拟的是20000的访问量(没敢模拟数字太大的访问量,怕把系统直接搞死哈哈哈哈),实际中可能会有远大于20000的访问量,当访问量更多的时候,甚至可能卡死服务,原因就是Tomcat的默认的工作线程数被打满了,没有多余的线程来分解压力和处理。

  而刚才做的压力测试还只是服务提供方8001自己实现的测试,如果此时是外部的服务消费方80来访问该服务,那么服务消费方只能够进行干等,消费方显然会对这样的等待时间不满意,服务提供方很有可能直接被拖死。我们发现8001自测都会出现问题,那如果我们再用服务消费方测试呢?

3.2.2、服务消费方进行压力测试:

  新建一个Module:cloud-consumer-feign-hystrix-order80作为服务消费方,修改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>
        <!--eureka client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <dependency>
            <groupId>com.atguigu.springcloud</groupId>
            <artifactId>cloud-api-common</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>

  YML:

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

  主启动:

package com.atguigu.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

/**
 * @create 2021-02-05 14:48
 */
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class OrderHystrixMain80 {
    public static void main(String[] args) {
        SpringApplication.run(OrderHystrixMain80.class, args);
    }
}

  服务消费方利用feign访问提供方的服务,编写对应的service接口如下:

package com.atguigu.springcloud.service;

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

/**
 * @create 2021-02-05 14:54
 */
@Component
@FeignClient("CLOUD-PROVIDER-HYSTRIX-PAYMENT")
public interface PaymentHystrixService {

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

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

  然后编写其Controller:

package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.service.PaymentHystrixService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * @create 2021-02-05 14:57
 */
@RestController
@Slf4j
public class OrderHystrixController {

    @Autowired
    private PaymentHystrixService paymentHystrixService;

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

    @GetMapping("/consumer/payment/hystrix/timeout/{id}")
    public String paymentInfo_TimeOut(@PathVariable("id") Long id) {
        String result = paymentHystrixService.paymentInfo_TimeOut(id);
        return result;
    }
}

  将80服务启动,用http://localhost/consumer/payment/hystrix/ok/1对服务提供方的 OK 服务进行访问,再进行压力测试,和之前一样,无法迅速访问该服务,如果压力测试中的线程数更多的时候,很可能会造成超时错误,出现以下错误提示:
在这里插入图片描述
  故障原因:8001同一层次的其他接口服务被困死,因为Tomcat线程池里面的工作线程已经被挤占完毕,80此时再调用8001,必然导致客户端访问响应缓慢。正是因为出现了这种现象,所以我们才需要服务降级、容错、服务限流等技术。

  如何解决,解决的要求?

  要求:

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

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

  解决:

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

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

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

  3.3、服务降级Fall Back

  3.3.1、服务端服务提供方的服务降级

  降级的配置用 @HystrixCommand 注解,在服务提供方自身找问题,设置自身调用超时时间的峰值,在峰值内可以正常运行,超过了峰值需要有兜底的方法处理,用作服务降级。

  首先在服务提供方的业务类上启用 @HystrixCommand 实现报异常后如何处理,也就是一旦调用服务方法失败并抛出了错误信息后,会自动调用 @HystrixCommand 标注好的fallbackMethod服务降级方法。在服务提供方的service中我们修改 TO 服务:

/**
 * 模拟复杂业务需要3秒钟
 * HystrixCommand配置3秒以内走正常的逻辑,超过3秒走服务降级逻辑
 * @param id
 * @return
 */
@HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",commandProperties = {
        @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
})
public String paymentInfo_TimeOut(Long id) {
    int time = 5;
    //暂停几秒钟线程,程序本身没有错误,就是模拟超时
    try {
        TimeUnit.SECONDS.sleep(time);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return "线程池: " + Thread.currentThread().getName() + " paymentInfo_TimeOut, id: " + id;
}

//兜底的方法
public String paymentInfo_TimeOutHandler(Long id) {
    return "系统忙,请稍后再试";
}

  然后在主启动类上添加 @EnableCircuitBreaker 注解对熔断器进行激活

package com.atguigu.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

/**
 * @create 2021-02-05 13:11
 */
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
public class PaymentHystrixMain8001 {
    public static void main(String[] args) {
        SpringApplication.run(PaymentHystrixMain8001.class, args);
    }
}

  TO服务的访问时间5秒,而我们用Hystrix配置的时间峰值为3秒,也就是当服务超时或服务出错时,会访问我们设置的fallbackMethod服务降级方法,再次访问TO服务 http://localhost:8001/payment/hystrix/timeout/31,我们发现其执行的方法确实为服务降级方法:
在这里插入图片描述
  3.3.2、客户端服务消费方的服务降级

  既然服务的提供方可以进行降级保护,那么服务的消费方,也可以更好的保护自己,也可以对自己进行降级保护,也就是说Hystrix服务降级既可以放在服务端(服务提供方),也可以放在客户端(服务消费方),但是!!!通常是用客户端做服务降级,下面在服务消费方即客户端配置自己的服务降级保护,修改80消费方的配置文件,添加如下配置已使其支持Hystrix:

feign:
  hystrix:
    enabled: true

  在80消费方的主启动类上添加 @EnableHystrix 激活Hystrix服务。

package com.atguigu.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

/**
 * @create 2021-02-05 14:48
 */
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@EnableCircuitBreaker
public class OrderHystrixMain80 {
    public static void main(String[] args) {
        SpringApplication.run(OrderHystrixMain80.class, args);
    }
}

  然后在80的Controller中同样加入**@HystrixCommand**注解已实现服务降级:

@GetMapping("/consumer/payment/hystrix/timeout/{id}")
@HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler", commandProperties = {
        @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1500")
})
public String paymentInfo_TimeOut(@PathVariable("id") Long id) {
    String result = paymentHystrixService.paymentInfo_TimeOut(id);
    return result;
}


/**
 * 兜底方法
 * @param id
 * @return
 */
public String paymentInfo_TimeOutHandler(Long id) {
    return "80系统忙,请稍后再试";
}

  也就是说如果消费方访问服务提供方的时间超过了1.5秒,那么就会访问自己的降级服务方法,访问:http://localhost/consumer/payment/hystrix/timeout/31。
在这里插入图片描述
3.3.3、统一全局服务降级方法

  而当前的这种处理方式是有问题的,也就是每个业务方法都对应了一个服务降级犯法,这会导致代码膨胀,所以我们应该定义一个统一的服务降级方法,统一的方法和自定义的方法分开。而且我们将服务降级方法和业务逻辑混合在了一起,这会导致代码混乱,业务逻辑不清晰。

  对于第一个问题,我们可以用feign接口中的 @DefaultProperties(defaultFallback = “”) 注解来配置全局的服务降级方法,也就是说自己配置过**@HystrixCommand(fallbackMethod = “”)** fallbackMethod方法的采用自己配置的服务降级方法,而没有配置过的就采用**@DefaultProperties(defaultFallback = “”)** 配置的全局的服务降级方法。这样的话通用的服务降级方法和独享的服务降级方法分开,避免了代码膨胀,合理减少了代码量,修改服务消费方80的Controller入下:

package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.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 lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * @create 2021-02-05 14:57
 */
@RestController
@Slf4j
@DefaultProperties(defaultFallback = "payment_Global_FallbackMethod") //全局服务降级
public class OrderHystrixController {

    @Autowired
    private PaymentHystrixService paymentHystrixService;

    @GetMapping("/consumer/payment/hystrix/ok/{id}")
    @HystrixCommand
    public String paymentInfo_OK(@PathVariable("id") Long id) {
        int i = 1/0; //手动模拟错误
        String result = paymentHystrixService.paymentInfo_OK(id);
        return result;
    }

    @GetMapping("/consumer/payment/hystrix/timeout/{id}")
    //定制降级服务
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1500")
    })
    public String paymentInfo_TimeOut(@PathVariable("id") Long id) {
        String result = paymentHystrixService.paymentInfo_TimeOut(id);
        return result;
    }


    /**
     * 定制服务降级方法
     * @param id
     * @return
     */
    public String paymentInfo_TimeOutHandler(Long id) {
        return "80系统忙,请稍后再试";
    }


    /**
     * 全局服务降级方法
     * @return
     */
    public String payment_Global_FallbackMethod() {
        return "全局异常处理信息";
    }

}

  paymentInfo_TimeOut由于定制了降级服务,所以访问服务提供方会出现超时(服务提供方提供的服务执行时间超过1.5秒),而paymentInfo_OK我们用 int i = 1/0; 这行代码模拟了错误,分别访问http://localhost/consumer/payment/hystrix/timeout/31 和http://localhost/consumer/payment/hystrix/ok/31,我们得到如下结果:
在这里插入图片描述
  可以看到由于paymentInfo_OK没有进行定制的服务降级方法,所以其访问的是全局服务降级方法,而paymentInfo_TimeOut访问的是定制服务降级方法,这里需要注意的是,无论是否配置了定制服务降级方法,都要在其服务上加入注解 @HystrixCommand, 否则服务降级和该服务没关系,比如paymentInfo_OK如果没有加入该注解,就直接会报除数为0错误。

  而对于第二个问题, 我们可以为Feign客户端定义的接口添加一个服务降级处理的实现类即可实现解耦,我们的80客户端已经有了PaymentHystrixService接口,我们新建一个类PaymentFallbackService实现该接口,并重写接口中的方法,为接口里的方法进行异常处理,并且我们在PaymentHystrixService声明其服务降级方法所在的类:

package com.atguigu.springcloud.service;

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

/**
 * @create 2021-02-05 14:54
 */
@Component
//当出现错误是到PaymentFallbackService类中找服务降级方法
@FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT",fallback = PaymentFallbackService.class)
public interface PaymentHystrixService {

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

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

  实现类:

package com.atguigu.springcloud.service;

import org.springframework.stereotype.Component;

/**
 * @create 2021-02-06 17:35
 */
@Component
public class PaymentFallbackService implements  PaymentHystrixService {
    @Override
    public String paymentInfo_OK(Long id) {
        return "paymentInfo_OK出现异常";
    }

    @Override
    public String paymentInfo_TimeOut(Long id) {
        return "paymentInfo_TimeOut出现异常";
    }
}

  然后我们关闭8001服务提供方服务,模拟服务器宕机

  测试:http://localhost/consumer/payment/hystrix/ok/31,http://localhost/consumer/payment/hystrix/timeout/31,由于全局异常处理设置仍然有效,所以ok会显示全局异常处理信息
在这里插入图片描述
  然后我们将Controller中耦合的代码都取消

package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.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 lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * @create 2021-02-05 14:57
 */
@RestController
@Slf4j
public class OrderHystrixController {

    @Autowired
    private PaymentHystrixService paymentHystrixService;

    @GetMapping("/consumer/payment/hystrix/ok/{id}")

    public String paymentInfo_OK(@PathVariable("id") Long id) {
        String result = paymentHystrixService.paymentInfo_OK(id);
        return result;
    }

    @GetMapping("/consumer/payment/hystrix/timeout/{id}")
    public String paymentInfo_TimeOut(@PathVariable("id") Long id) {
        String result = paymentHystrixService.paymentInfo_TimeOut(id);
        return result;
    }

}

  再次测试,如图,在服务访问出现错误时,访问了我们配置的PaymentFallbackService类中的服务降级方法,这样就实现了代码的解耦,使业务逻辑不再混乱
在这里插入图片描述
  3.4、服务熔断Break

  3.4.1、熔断机制概述

  熔断机制是应对雪崩效应的一种微服务链路保护机制,当扇出链路的某个微服务出错不可用或者响应时间太长时,会进行服务的降级,进而熔断该节点微服务的调用,也就是说服务熔断会导致服务降级,快速返回错误的响应信息。当检测到该节点微服务调用响应正常后,恢复调用链路。也就是说,服务熔断在服务好了之后会重新允许访问服务。在SpringCloud框架中,熔断机制通过Hystrix实现。Hystrix会监控微服务间的调用状况,当失败的调用到一定阈值,缺省是5秒内20次调用失败,就会启动熔断机制。熔断机制的注解是 @HystrixCommand。关于熔断机制,具体可以参考论文CircuitBreaker。

  3.4.2、实操

   修改cloud-provider-hystrix-payment8001服务提供方的Service中添加如下代码:

//======服务熔断

/**
 * fallbackMethod                               服务降级方法
 * circuitBreaker.enabled                       是否开启断路器
 * circuitBreaker.requestVolumeThreshold        请求次数
 * circuitBreaker.sleepWindowInMilliseconds     时间窗口期
 * circuitBreaker.errorThresholdPercentage      失败率达到多少后跳闸
 * 以下配置意思是在10秒时间内请求10次,如果有6此是失败的,就触发熔断器
 * 注解@HystrixProperty中的属性在com.netflix.hystrix.HystrixCommandProperties类中查看
 * @param id
 * @return
 */
@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") Long id) {
    if (id < 0) {
        throw new RuntimeException("id 不能为负数");
    }
    String serialNumber = IdUtil.simpleUUID();
    return Thread.currentThread().getName() + " 调用成功,流水号: " + serialNumber;
}

/**
 * 服务熔断触发的服务降级方法
 * @param id
 * @return
 */
public String paymentCircuitBreaker_fallback(@PathVariable("id") Long id) {
    return "id 不能为负数,请稍后再试。id:" + id;
}

  在 @HystrixCommand 注解中配置熔断机制的参数,配置的参数含义如下:

属性名含义默认值
circuitBreaker.enabled是否开启断路器true
circuitBreaker.requestVolumeThreshold请求次数20
circuitBreaker.sleepWindowInMilliseconds时间窗口期5000
circuitBreaker.errorThresholdPercentage失败率达到多少后跳闸50

  这些属性名的具体含义一级其默认值可以在 com.netflix.hystrix.HystrixCommandProperties 类中进行查看。而我们在service中配置的意思就是在10秒时间内请求10次,如果有6次是失败的,就触发熔断器。

  在Controller中添加该服务:

    @GetMapping("payment/circuit/{id}")
    public String paymentCircuitBreaker(@PathVariable("id") Long id) {
        String result = paymentService.paymentCircuitBreaker(id);
        log.info("=========result:" + result);
        return result;
    }

3.4.3、测试

  根据我们的业物逻辑,也就是当我们的id为整数时,服务可以正常访问,而当id为负数时,访问服务出错。我们先访问 http://localhost:8001/payment/circuit/1 代表正确的服务请求,可以发现一切正常!!!:
在这里插入图片描述
  然后我们进行大量的错误访问,强行触发服务熔断,然后在进行正确的访问。
在这里插入图片描述
  我们发现在进行超出我们阈值的错误访问后,触发了服务熔断,即使再进行正确的访问也无法进行,但是一定时间后,正确的服务访问又可以顺利进行,这就是服务熔断的整体过程:在触发了服务熔断后,先进行服务的降级,再逐渐恢复调用链路。

  3.4.4、总结

  结合官网中对熔断机制的描述,其熔断过程可以如下描述:

  熔断器打开和关闭的精确方式如下:

    1.假设电路上的访问达到某个阈值(HystrixCommandProperties.circuitBreakerRequestVolumeThreshold())…

    2.并假设误差百分比超过阈值误差百分比(HystrixCommandProperties.circuitBreakerErrorThresholdPercentage())…

    3.然后,断路器从CLOSED为OPEN,触发熔断机制。

    4.当它断开时,它会使针对该断路器的所有请求短路。

    5.经过一段时间(HystrixCommandProperties.circuitBreakerSleepWindowInMilliseconds())后,下一个单个请求被允许通过(这是HALF-OPEN状态)。如果请求失败,断路器将OPEN在睡眠窗口期间返回到该状态。如果请求成功,则断路器切换到,CLOSED,并且1.**中的逻辑再次接管。

也就是在熔断机制中,熔断器分为三个状态:

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

  下面是官网上的熔断器流程图:
在这里插入图片描述
  那么熔断器在什么情况下开始起作用呢?

  涉及到熔断器的三个重要参数:

  1.快照时间窗口期circuitBreaker.sleepWindowInMilliseconds:熔断器是否打开需要统计一些请求和错误数据,而统计的时间范围就是快找时间窗,默认为最近的10秒;

  2.请求总数阈值circuitBreaker.requestVolumeThreshold:在快照时间窗内,必须满足请求总数阈值才有资格触发熔断,默认为20次,这意味着在快照时间窗规定的时间内,如果该Hystrix命令的调用次数不足20次,即使所有请求都超时或其他原因失败,熔断器都不会打开;

  3.错误百分比阈值circuitBreaker.errorThresholdPercentage:当请求总数在快照时间窗内超过了阈值,且在这些调用中,超过错误百分比阈值比例的错误调用,熔断器就会打开。

  熔断器打开后再有请求调用的时候,将不会调用主逻辑,而是直接调用服务降级的方法,实现了自动发现错误并将降级逻辑切换为主逻辑,减少响应延迟的效果。

  在熔断器打开后,原来的主逻辑如何恢复呢?

  当熔断器打开后,对主逻辑进行熔断之后,Hystrix会启动一个 休眠时间窗(5秒) , 在这个时间窗内,降级逻辑是临时的主逻辑,当休眠时间窗到期,熔断器会进入半开状态,释放一次请求到原来的主逻辑上,如果此次请求能够正常访问,则熔断器会进入闭合状态,从而恢复主逻辑,如果注册请求依然有问题,则熔断器继续保持打开状态,并且休眠时间窗重新计时。

  ALl配置:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

4、Hystrix工作流程

整体的Hystrix工作流程图入下:
在这里插入图片描述
中文版:

流程说明:

  1.每次调用创建一个新的HystrixCommand,把依赖调用封装在run()方法中.

  2.执行execute()/queue做同步或异步调用.

  3.当前调用是否已被缓存,是则直接返回结果,否则进入步骤 4

  4.判断熔断器(circuit-breaker)是否打开,如果打开跳到步骤 8,进行降级策略,如果关闭进入步骤 5

  5.判断线程池/队列/信号量是否跑满,如果跑满进入降级步骤8,否则继续后续步骤 6

  6调用HystrixCommand的run方法.运行依赖逻辑

    6.1. 调用是否出现异常,否:继续,是进入步骤8,

    6.2. 调用是否超时,否:返回调用结果,是进入步骤8

  1、搜集5、6步骤所有的运行状态(成功, 失败, 拒绝,超时)上报给熔断器,用于统计从而判断熔断器状态

  2、getFallback()降级逻辑.四种触发getFallback调用情况(图中步骤8的箭头来源):返回执行成功结果

5、服务监控hystrix Dashboard

  除了隔离依赖服务的调用以外,Hystrix还提供了准实时的调用监控——Hystrix Dashboard,Hystrix会持续的记录所有通过Hystrix发起的请求的执行信息,并以统计报表和图形的形式展示给用户,包括每秒执行多少请求,多少成功,多少失败等。SpringCloud也提供了Hystrix Dashboard的整合,对监控内容转化成可视化界面。

  5.1、新建Module:cloud-consumer-hystrix-dashboard9001作为Hystrix Dashboard服务

  5.2、添加Hystrix Dashboard的依赖: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>
    <description>hystrix监控</description>
    
    <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>

  5.3、写配置文件application.yml,加个端口即可:

server:
  port: 9001

  5.4、编写主启动类,在主启动类上添加@EnableHystrixDashboard注解开启Hystrix Dashboard功能:

package com.atguigu.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;

/**
 * @create 2021-02-07 14:16
 */
@SpringBootApplication
@EnableHystrixDashboard
public class HystrixDashboardMain9001 {
    public static void main(String[] args) {
        SpringApplication.run(HystrixDashboardMain9001.class);
    }
}

  5.5、所有的服务提供方微服务(如我们的8001/8002)都需要监控依赖配置:

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

  访问 http://localhost:9001/hystrix 我们就可以看见Hystrix Dashboard的图形化界面
在这里插入图片描述
  为了让服务提供方的服务能被Hystrix Dashboard监控到,需要在提供方服务的主启动类中添加如下配置,这里我们使用cloud-provider-hystrix-payment8001:

/**
     *此配置是为了服务监控而配置,与服务容错本身无关,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;
    }

  在Hystrix Dashboard的图形化界面中输入要监控的服务提供者:http://localhost:8001/hystrix.stream
在这里插入图片描述
  测试地址:http://localhost:8001/payment/circuit/1,http://localhost:8001/payment/circuit/-1
在这里插入图片描述
  监控结果,成功时:Closed状态
在这里插入图片描述
  监控结果,失败时:Open状态
在这里插入图片描述
  7色:
在这里插入图片描述
  1圈:
在这里插入图片描述
  1线:
在这里插入图片描述
整图说明1:
在这里插入图片描述
在这里插入图片描述
  整图说明2:
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值