SpringCloud 学习第十三节 Hystrix断路器

概述

分布式系统面临的问题

    对于复杂的分布式体系结构中的应用程序,可能有数十个依赖关系,每个依赖关系在某些时候不可避免的发生失败(例如 网络卡顿、网络调用超时、程序出错)。
    服务雪崩
    多个微服务之间调用的时候,假设微服务A调用微服务B和微服务C,微服务B、C又调用了其它微服务,这就是所谓的“扇出”,如果扇出的链路上某个微服务调用的响应时间过长,或者不可用,对于微服务A的调用就会占用越来越多的系统资源,进而引起系统崩溃,造成雪崩效应
    对于高流量的应用来说,单一的后端依赖可能会导致所有服务器上的所有资源在几秒钟内饱和,比失败更加糟糕的是,这些应用程序还可能导致服务之间的延迟增加,备份队列、线程和其它系统资源紧张,导致整个系统发生更多的级联故障。这些都表示需要对故障和延迟进行隔离管理,即便单个依赖关系的失败,不能导致整个应用程序或系统崩溃。通常情况下,一个模块下某个的实例失败后,这个时候该模块依旧还会接收流量,然后这个有问题的模块还调用了其它模块,这样就会发生级联故障,或者叫雪崩。

Hystrix 是什么

    Hystrix是一个用于处理分布式系统的延迟容错的开源库,在分布式系统中,许多依赖在某些时候不可避免的发生失败,比如超时、异常等,Hystrix能够保证在一个依赖出现问题的情况下,不会导致整体服务失败,避免级联故障,以提高分布式系统的弹性。
    断路器本身是一种开关装置,当某个服务单元发生故障后,通过断路器的故障监控(类似于熔断保险丝),向调用方返回一个符合预期的、可处理的备选响应(FallBack),而不是长时间的等待或者抛出调用方无法处理的异常。这样就保证了服务调用方的线程不会被长时间、不必要的占用,从而避免了故障在系统中的蔓延,乃至雪崩。
    Hystrix 的主要作用,服务降级,服务熔断,接近实时的监控
    官网资料https://github.com/Netflix/Hystrix/wiki/How-To-Use

Hystrix 简要概念

     服务降级
     服务降级是当服务器压力剧增的情况下,根据当前业务情况及流量对一些服务和页面有策略的降级,以此释放服务器资源以保证核心任务的正常运行。fallback 服务降级,不让客户端持续等待,返回一个提示,导致服务降级的原因有:1、程序运行时异常 2、超时 3、服务熔断触发服务降级 4、线程池/信号量打满也会导致服务器降级
     服务熔断
     达到最大访问量以后,服务出现不可用或响应超时的情况时,为了防止整个系统出现雪崩,直接拒绝访问,调用服务降级方法
     服务熔断是分步骤进行的 服务降级–>进而熔断—>恢复链路调用
     服务限流
     服务发生高并发操作时,避免请求瞬间拥挤进入,根据设置的规则,比如每秒钟进入5个请求,有序进行。其余排队等待

Hystrix 案例

    电脑启动5个微服务和docker 内存压力有的大,Eureka 不再使用集群版,仅使用7001,修改一下7001的application.xml,不再守望7002

server:
  port: 7001
# eureka 服务端的实例名称
eureka:
  instance:
    hostname: eureka7001.com  # eureka 服务端的实例名称
  client:
    # false 表示不向注册中心注册自己
    register-with-eureka: false
    # false 表示自己就是注册中心,职责是维护服务实例,无需去检索服务
    fetch-registry: false
    # 设置与eureka Server交互的地址查询服务和注册服务都需要依赖这个地址
    service-url:
      # 7001与7002 相互守望 相互注册
      defaultZone: http://eureka7001.com:7001/eureka/
#  server:
#    # 出厂默认是开启自我保护机制的,eureka.server.enable-self-preservation=false 可以禁用自我保护模式
#    # 关闭自我保护机制,保证不可用服务被及时清除
#    enable-self-preservation: false
#    # 过期实例应该启动并运行的时间间隔, 也就是清理无效节点的时间间隔  单位为毫秒, 默认60s 改成1s
#    eviction-interval-timer-in-ms: 1000

新建服务提供者Module

    cloud-provider-hystrix-payment8001

pom.xml 修改

<?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>zjt-cloud-api</artifactId>
        <groupId>com.zjt.cloud-api</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-provider-hystrix-payment8001</artifactId>

    <dependencies>
        <dependency><!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
            <groupId>com.zjt.cloud-api</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <!--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>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </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>

application.yml 编写

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.zjt.cloud;

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

import java.util.TimeZone;

/**
 * @author zjt
 * @date 2020-09-08
 */
@SpringBootApplication
@EnableEurekaClient
public class PaymentHystrix8001Application {

    public static void main(String[] args) {
        // 时区设置
        TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
        SpringApplication.run(PaymentHystrix8001Application.class, args);
    }
    
}

业务类

     模拟service
     service接口

package com.zjt.cloud.service;

/**
 * @author zjt
 * @date 2020-09-08
 */
public interface PaymentService {

    String paymentInfoOk(Integer id);

    String paymentTimeout(Integer id, Integer seconds);

}

     service 实现类

package com.zjt.cloud.service.impl;

import com.zjt.cloud.service.PaymentService;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author zjt
 * @date 2020-09-08
 */
@Service
public class PaymentServiceImpl implements PaymentService {

    @Override
    public String paymentInfoOk(Integer id) {
        return "正常方法->线程池:" + Thread.currentThread().getName() + ",paymentInfoOk->" + id;
    }

    @Override
    public String paymentTimeout(Integer id, Integer seconds) {
        try {
            // 模拟长业务流程 线程睡眠 seconds 单位秒
            TimeUnit.SECONDS.sleep(seconds);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "超时方法->线程池:" + Thread.currentThread().getName() + ",paymentTimeout->" + id;
    }

}

     controller

package com.zjt.cloud.controller;

import com.zjt.cloud.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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zjt
 * @date 2020-09-08
 */
@Slf4j
@RestController
@RequestMapping("/payments-hystrix")
public class PaymentHystrixController {

    @Autowired
    private PaymentService paymentService;

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


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

    @GetMapping("/{id}/timeout")
    public String paymentTimeout(@PathVariable Integer id, Integer seconds) {
        String result = paymentService.paymentTimeout(id, seconds);
        log.info(result + "  " + port);
        return result;
    }


}

测试

     自测 两个接口都是正常
在这里插入图片描述

在这里插入图片描述
     jmeter 压力测试 官网https://jmeter.apache.org/ 可以直接下载解压使用
     jmeter 新建线程组 200个 循环200次
在这里插入图片描述
     200个线程 循环200次 共4万次请求
在这里插入图片描述
     添加HTTP 请求
在这里插入图片描述

在这里插入图片描述
     启动测试 然后在请求正常的返回 开始出现明显卡顿,这里有可能我的电脑配置低,可以增加线程数 比如 1024个线程 再测试
在这里插入图片描述
     此时仅是8001 服务的自测,同样消费者调用8001提供的服务,那么消费者也只能等到8001处理,消费者也被8001拖累。将消费者模块加入,并做并发实验。

新建服务消费者Module

     cloud-consumer-feign-hystrix-order80

pom.xml 修改

<?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>zjt-cloud-api</artifactId>
        <groupId>com.zjt.cloud-api</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-consumer-feign-hystrix-order80</artifactId>

    <dependencies>
        <!--openfeign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <!--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>
        <!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
        <dependency>
            <groupId>com.zjt.cloud-api</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <!--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>

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

application.yml 编写

server:
  port: 80

spring:
  application:
    name: consumer-order-hystrix

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

#feign:
#  hystrix:
#    enabled: true

# ribbon 的超时设置不配置,使用默认的配置1s超时

主启动类

package com.zjt.cloud;

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

import java.util.TimeZone;

/**
 * @author zjt
 * @date 2020-09-09
 */
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class ConsumerHystrix80Application {

    public static void main(String[] args) {
        TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
        SpringApplication.run(ConsumerHystrix80Application.class, args);
    }
}

业务类

     远程调用接口

package com.zjt.cloud.rpcserver;

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

/**
 * @author zjt
 * @date 2020-09-09
 */
@FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT")
public interface PaymentRPCLocalCall {

    @GetMapping("/payments-hystrix/{id}/ok")
    String paymentInfoOk(@PathVariable(value = "id") Integer id);

    @GetMapping("/payments-hystrix/{id}/timeout")
    String paymentTimeout(@PathVariable(value = "id") Integer id,  @RequestParam(value = "seconds") Integer seconds);

}

    controller

package com.zjt.cloud.controller;

import com.zjt.cloud.rpcserver.PaymentRPCLocalCall;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zjt
 * @date 2020-09-09
 */
@RestController
@RequestMapping("/consumer-hystrix")
public class ConsumerHystrixController {

    @Autowired
    private PaymentRPCLocalCall paymentRPCLocalCall;

    @GetMapping("/{id}/ok")
    public String paymentInfoOk(@PathVariable(value = "id") Integer id) {
        return paymentRPCLocalCall.paymentInfoOk(id);
    }

    @GetMapping("/{id}/timeout")
    public String paymentTimeout(@PathVariable(value = "id") Integer id, Integer seconds) {
        return paymentRPCLocalCall.paymentTimeout(id, seconds);
    }

}

测试

    自测通过
在这里插入图片描述

    开启jmeter压力测试,请求8001 在测试80 项目已经开始有超时问题出现,原因是8001服务提供者其它接口被阻塞,8001 tomcat 的工作线程基本被挤占完毕。
在这里插入图片描述

解决问题

需要解决的问题要求

    1、超时导致服务器变慢 ->超时不再等待,服务提供者超时,服务消费者不能一直等待,需要服务降级
    2、出错(宕机或程序运行时异常)->出错要有另外解决方案,服务提供者出错,消费者不能等待或者返回错误页面,需要服务降级。服务提供者正常返回,消费者自己出现故障或者有自我要求,自己等待时间小于服务提供者所需时间,自己需要服务降级

服务降级

    主启动类添加 @EnableHystrix 注解

package com.zjt.cloud;

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

import java.util.TimeZone;

/**
 * @author zjt
 * @date 2020-09-08
 */
@SpringBootApplication
@EnableEurekaClient
@EnableHystrix
public class PaymentHystrix8001Application {

    public static void main(String[] args) {
        // 时区设置
        TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
        SpringApplication.run(PaymentHystrix8001Application.class, args);
    }
}

     修改hystrix服务提供者8001 代码添加服务降级方法和配置 ,业务类修改

package com.zjt.cloud.service.impl;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.zjt.cloud.service.PaymentService;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author zjt
 * @date 2020-09-08
 */
@Service
public class PaymentServiceImpl implements PaymentService {

    @Override
    public String paymentInfoOk(Integer id) {
        return "正常方法->线程池:" + Thread.currentThread().getName() + ",paymentInfoOk->" + id;
    }

    @Override
    // 启用Hystrix服务降级,指定方法运行最长时间,超时或出现程序运行时异常 调用 服务降级方法 paymentTimeoutFallBack()
    @HystrixCommand(fallbackMethod = "paymentTimeoutFallBack", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
    })
    public String paymentTimeout(Integer id, Integer seconds) {
        // int i = 10 / 0; 
        try {
            // 模拟长业务流程 线程睡眠 seconds 单位秒
            TimeUnit.SECONDS.sleep(seconds);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "超时方法->线程池:" + Thread.currentThread().getName() + ",paymentTimeout->" + id;
    }
	
	// 服务降级方法,参数必须保持和主方法一致,否则Hystrix在调用时将抛出错误
    private String paymentTimeoutFallBack(Integer id, Integer seconds) {
        return "8001降级方法->线程池:" + Thread.currentThread().getName() + ",paymentTimeout->" + id;
    }
}

    测试 传入seconds 5秒 但是hystrix 8001设置超时时间是4秒,响应时间过长需要走降级方法
在这里插入图片描述
    Hystrix服务降级在服务提供者侧做,约定响应时间后,服务消费者一般不再需要服务降级,但是消费者为了更好的保护自己,也可以做服务降级,例如服务提供者4秒中内提供服务认为是正常的,但是消费者最大等待时间只希望是2秒,超时走自己的降级方法
    消费者80 application.yml 修改

server:
  port: 80

spring:
  application:
    name: consumer-order-hystrix

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

feign:
  hystrix:
    enabled: true

# open feign 默认支持ribbon 超时控制交给ribbon 设置feign客户端超时时间
ribbon:
  # 建立链接后从服务器读取到可用资源所用的时间
  ReadTimeout: 5000
  # 建立链接所用的时间,用户网络正常的情况下,两端连接所用的时间
  ConnectTimeout: 5000
# hystrix 设置最大响应时间 默认是1s hystrix此设置项是map结构,所以没有提示
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 5000

    主启动类添加 @EnableHystrix 注解

package com.zjt.cloud;

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

import java.util.TimeZone;

/**
 * @author zjt
 * @date 2020-09-09
 */
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@EnableHystrix
public class ConsumerHystrix80Application {

    public static void main(String[] args) {
        TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
        SpringApplication.run(ConsumerHystrix80Application.class, args);
    }

}

     业务类 controller修改

    @GetMapping("/{id}/timeout")
    @HystrixCommand(fallbackMethod = "paymentTimeoutFallBacks", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000")
    })
    public String paymentTimeout(@PathVariable(value = "id") Integer id, Integer seconds) {
        String s = paymentRPCLocalCall.paymentTimeout(id, seconds);
        log.info(s);
        return s;
    }

    private String paymentTimeoutFallBacks(Integer id, Integer seconds) {
        return "80端降级方法->线程池:" + Thread.currentThread().getName() + ",paymentTimeout->" + id;
    }

     测试 响应时间 在两秒以内的,正常返回结果
在这里插入图片描述
     测试 响应时间超过两秒的,走自己的降级方法
在这里插入图片描述

全局服务降级

     目前的问题 1、服务降级方法根业务逻辑耦合在一起代码混乱。2、每个方法都需要自己的服务降级方法,代码膨胀
     针对于代码膨胀,每一个服务降级的方法都需要有自己的服务降级方法,hystrix提供了全局的处理方法,业务代码如下

package com.zjt.cloud.controller;

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 com.zjt.cloud.rpcserver.PaymentRPCLocalCall;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zjt
 * @date 2020-09-09
 */
@Slf4j
@RestController
@RequestMapping("/consumer-hystrix")
// 设置默认的全部服务降级方法 目前测试,该方法仅能调用自己的类中的方法,还没有找到调用其它类中的方法
// 指定的方法必须是无参数的
@DefaultProperties(defaultFallback = "fallBackMethod", commandProperties = {
        // 设置全局 响应超时时间
        @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000")
})
public class ConsumerHystrixController {

    @Autowired
    private PaymentRPCLocalCall paymentRPCLocalCall;

    @GetMapping("/{id}/ok")
    public String paymentInfoOk(@PathVariable(value = "id") Integer id) {
        return paymentRPCLocalCall.paymentInfoOk(id);
    }

    @GetMapping("/{id}/timeout")
    
//    @HystrixCommand(fallbackMethod = "paymentTimeoutFallBacks", commandProperties = {
//            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000")
//    })
	//启用HystrixCommand 无需指定 降级的方法
    @HystrixCommand
    public String paymentTimeout(@PathVariable(value = "id") Integer id, Integer seconds) {
        String s = paymentRPCLocalCall.paymentTimeout(id, seconds);
        log.info(s);
        return s;
    }

    private String paymentTimeoutFallBacks(Integer id, Integer seconds) {
        return "80端降级方法->线程池:" + Thread.currentThread().getName() + ",paymentTimeout->" + id;
    }

    private String fallBackMethod() {
        return "通用服务降级处理方法->controller";
    }
}

     测试 服务调用超时测试
在这里插入图片描述
     个人认为在服务提供者端,使用这样的方法可行,针对不同的业务,提供不同的服务降级方法。但是消费者服务可能调用多个服务提供者组合数据并返回,其中一个微服务正常返回数据信息,而另一个微服务无响应(比如宕机),此时直接到自身降级方法处理并不合适。进行代码块拆分,那么将会更加的混乱。
     FeignClient也提供了服务降级方法 @FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT", fallback = PaymentRPCLocalCallImpl.class) 并且
实现接口,可解决代码混乱,但感觉这样代码冗余没有较好的避免。但是逻辑清晰。

package com.zjt.cloud.rpcserver;

import com.zjt.cloud.rpcserver.impl.PaymentRPCLocalCallImpl;
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;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @author zjt
 * @date 2020-09-09
 */
@Component
@FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT", fallback = PaymentRPCLocalCallImpl.class)
public interface PaymentRPCLocalCall {

    @GetMapping("/payments-hystrix/{id}/ok")
    String paymentInfoOk(@PathVariable(value = "id") Integer id);

    @GetMapping("/payments-hystrix/{id}/timeout")
    String paymentTimeout(@PathVariable(value = "id") Integer id, @RequestParam(value = "seconds") Integer seconds);

}
package com.zjt.cloud.rpcserver.impl;

import com.zjt.cloud.rpcserver.PaymentRPCLocalCall;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author zjt
 * @date 2020-09-10
 */
@Slf4j
@Component
public class PaymentRPCLocalCallImpl implements PaymentRPCLocalCall {


    @Override
    public String paymentInfoOk(Integer id) {
        String s = "PaymentRPCLocalCallImpl fall back paymentInfoOk";
        log.info(s);
        return s;
    }
    
    @Override
    public String paymentTimeout(Integer id, Integer seconds) {
        String s = "PaymentRPCLocalCallImpl fall back paymentTimeout";
        log.info(s);
        return s;
    }
    
}

     测试
在这里插入图片描述
     将8001服务提供者断开连接,将直接走降级方法
在这里插入图片描述
在这里插入图片描述

服务熔断

     服务熔断机制概述:熔断机制是应对雪崩效应的一种微服务链路保护机制。当扇出链路的某个微服务出错或者不可用或者响应时间太长时,会进行服务的降级,进而熔断该节点微服务的调用,快速返回错误的响应信息。当检测到该节点微服务调用响应正常后,恢复调用链路。
    在Spring Cloud框架中,熔断机制通过Hystrix实现,Hystrix会监控微服务间的调用状况,当失败的调用达到一定阈值,缺省是5秒20次调用失败,就会启动熔断机制,熔断机制的注解是@HystrixCommand
    下图是Hystrix断路器的工作模式图,我的理解是首先断路器是处于关闭状态的,当服务调用出错或者响应时间太长达到阈值,断路器打开,所有请求全部走降级方法,Hystrix断路器在开启和关闭之间有一个半开状态,会释放一些请求到正常方法中,调用成功Hystrix断路器将会关闭,调用失败,断路器继续打开。
官方解释https://github.com/Netflix/Hystrix/wiki/How-it-Works#CircuitBreaker
    The precise way that the circuit opening and closing occurs is as follows:
    1、Assuming the volume across a circuit meets a certain threshold (HystrixCommandProperties.circuitBreakerRequestVolumeThreshold())…
    2、And assuming that the error percentage exceeds the threshold error percentage (HystrixCommandProperties.circuitBreakerErrorThresholdPercentage())…
    3、Then the circuit-breaker transitions from CLOSED to OPEN.
    4、While it is open, it short-circuits all requests made against that circuit-breaker.
    5、After some amount of time (HystrixCommandProperties.circuitBreakerSleepWindowInMilliseconds()), the next single request is let through (this is the HALF-OPEN state). If the request fails, the circuit-breaker returns to the OPEN state for the duration of the sleep window. If the request succeeds, the circuit-breaker transitions to CLOSED and the logic in 1. takes over again.

    Hystrix 断路器打开和关闭的精确方式如下
    1、在时间窗口期内断路器 的最小请求数达到阈值(HystrixCommandProperties.circuitBreakerRequestVolumeThreshold())…
    2、并且错误请求数百分比超过设定值(HystrixCommandProperties.circuitBreakerErrorThresholdPercentage())…
    3、Hystrix 断路器从关闭变成打开状态
    4、当断路器打开时,所有请求将会短路(也就是走降级方法)
    5、当经过设置的时间休眠窗口时间(HystrixCommandProperties.circuitBreakerSleepWindowInMilliseconds()), 下一次单个的请求将会被允许通过 (this is the HALF-OPEN state)这就是半开状态 。如果请求失败, 在睡眠窗口期间,断路器返回打开状态,如果请求成功,则断路器切换到关闭状态,并且1.中的逻辑再次接管。

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

    使用熔断,业务层

package com.zjt.cloud.service.impl;

import cn.hutool.core.util.IdUtil;
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 com.zjt.cloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zjt
 * @date 2020-09-08
 */
@Slf4j
@Service
@DefaultProperties(defaultFallback = "paymentCircuitBreakerFallBack", commandProperties = {
        @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),// 是否开启断路器
        //用来设置在滚动时间窗中,断路器熔断的最小请求数。例如,默认该值为20的时候,如果滚动时间窗(默认10秒)内仅收到19个请求,
        // 即使这19个请求都失败了,断路器也不会打开
        @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
        // 用来设置当断路器打开之后的休眠时间窗。休眠时间窗结束之后,会将断路器设置为“半开”状态,尝试熔断的请求命令,
        // 如果依然时候就将断路器继续设置为“打开”状态,如果成功,就设置为“关闭”状态。
        @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
        // 用来设置断路器打开的错误百分比条件。默认值为50,表示在滚动时间窗中,在请求值超过requestVolumeThreshold阈值的前提下,
        // 如果错误请求数百分比超过50,就把断路器设置为“打开”状态,否则就设置为“关闭”状态。
        @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60")
        // 更加详细的配置和解释 参照com.netflix.hystrix.HystrixCommandProperties
})
public class PaymentServiceImpl implements PaymentService {

    private final AtomicInteger atomicInteger = new AtomicInteger(0);

    @Override
    public String paymentInfoOk(Integer id) {
        return "正常方法->线程池:" + Thread.currentThread().getName() + ",paymentInfoOk->" + id;
    }

    // 服务降级
    @Override
    @HystrixCommand(fallbackMethod = "paymentTimeoutFallBack", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "4000")
    })
    public String paymentTimeout(Integer id, Integer seconds) {
        //int i = 10 / 0;
        try {
            // 模拟长业务流程 线程睡眠 seconds 单位秒
            TimeUnit.SECONDS.sleep(seconds);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "超时方法->线程池:" + Thread.currentThread().getName() + ",paymentTimeout->" + id;
    }

    private String paymentTimeoutFallBack(Integer id, Integer seconds) {
        return "8001降级方法->线程池:" + Thread.currentThread().getName() + ",paymentTimeout->" + id;
    }

    // 服务熔断
    @Override
    @HystrixCommand
    public String paymentCircuitBreaker(Integer id) {
        if (id < 1) {
            throw new RuntimeException("id 必须大于0 \t id ->" + id);
        }
        return Thread.currentThread().getName() + "\t" + "UUID->" + IdUtil.fastSimpleUUID();
    }

    public String paymentCircuitBreakerFallBack() {
        return Thread.currentThread().getName() + "\t" + "id 必须大于0,请重新尝试";
    }

}

    controller

 @GetMapping("/circuit/{id}")
    public String paymentCircuitBreaker(@PathVariable Integer id) {
        log.info("id->" + id);
        String result = paymentService.paymentCircuitBreaker(id);
        log.info(result);
        return result;
    }

    测试:先发送请求id<1的触发熔断,之后在发送正常请求
在这里插入图片描述
    总结
    熔断的三种状态:1、熔断关闭,熔断关闭时正常的业务处理流程,不会对服务进行熔断。2、熔断打开,不再执行当前业务流程,直接降级,当内部设置时钟(MTTR)平均故障处理时间,当时长达到时钟设置时间,处于熔断半开状态。3、熔断半开,处于熔断半开时,下一次单个的请求将会被允许通过 (this is the HALF-OPEN state)这就是半开状态。

服务监控 HystrixDashboard

    除了隔离依赖服务的调用以外,Hystrix还提供了准时的调用监控(Hystrix Dashboard),Hystrix会持续的记录游泳功过Hystrix发起的请求的执行信息,并以统计报表和图形的形式展示给用户,包括每秒执行了多少请求,多少成功、多少失败等等,Netflix通过Hystrix-metrics-event-stream项目实现了对以上指标的监控,SpringCloud也提供了Hystrix Dashboard的整合,对监控内容转化成为可视化界面。
    搭建9001图形化监控模块
    建module
    cloud-consumer-hystrix-dashboard9001
    改pom.xml

<?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>zjt-cloud-api</artifactId>
        <groupId>com.zjt.cloud-api</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-consumer-hystrix-dashboard9001</artifactId>

    <dependencies>
        <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.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>

    application.yml

server:
  port: 9001

    主启动类

package com.zjt.cloud;

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

import java.util.TimeZone;

/**
 * @author zjt
 * @date 2020-09-11
 */
@SpringBootApplication
@EnableHystrixDashboard
public class HystrixDashboard9001Application {

    public static void main(String[] args) {
        // 时区设置
        TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
        SpringApplication.run(HystrixDashboard9001Application.class, args);
    }

}

    8001被监控的主启动类修改

package com.zjt.cloud;

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.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.context.annotation.Bean;

import java.util.TimeZone;

/**
 * @author zjt
 * @date 2020-09-08
 */
@SpringBootApplication
@EnableEurekaClient
@EnableHystrix
public class PaymentHystrix8001Application {

    public static void main(String[] args) {
        // 时区设置
        TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
        SpringApplication.run(PaymentHystrix8001Application.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;
    }

}

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

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值