• 1. Hystrix理解
    • 1.1 概述
    • 1.2 背景
    • 1.3 雪崩效应常见场景
    • 1.4 雪崩效应应对策略
    • 1.5 初探Hystrix
    • 1.6 Hystrix流程图
  • 2. 构建问题项目
    • 2.2 构建cloud-provider-hystrix-payment8007项目
      • 2.2.1 pom文件
      • 2.2.2 yml文件
      • 2.2.3 启动类
      • 2.2.4 控制器
      • 2.2.5 普通测试
      • 2.2.6 高并发测试
    • 2.3 构建cloud-consumer-hystrix-order6007项目
      • 2.3.1 pom文件
      • 2.3.2 yml文件
      • 2.3.3 启动类
      • 2.3.4 Feign的Service接口
      • 2.3.5 控制器
      • 2.3.6 普通测试
      • 3.2.7 对8007高并发测试
  • 3 服务降级
    • 3.1 概述
    • 3.2 服务提供者8007服务降级(超时)
      • 3.2.1 启动类
      • 3.2.2 控制器类
      • 3.2.3 测试
    • 3.3 服务消费者6007服务降级(异常)
      • 3.3.1 启动类
      • 3.3.2 控制器
      • 3.3.3 测试
    • 3.4 简化代码结构
      • 3.4.1 默认Fallback方法
      • 3.4.2 OpenFeign与Hystrix合用
  • 4. 服务熔断
    • 4.1 概述
    • 4.1.1 熔断器是什么
      • 4.1.2 熔断器状态
      • 4.1.3 执行过程
    • 4.2 案例演示
      • 4.2.1 HystrixController
      • 4.2.2 测试
      • 4.2.3 熔断器全部配置
  • 5. 服务监控HystrixDashboard
    • 5.1 新建cloud-hystrix-dashboard9001模块
      • 5.1.1 pom文件
      • 5.1.2 yml文件
      • 5.1.3 启动类
    • 5.2 修改被监控项目cloud-provider-hystrix-payment8007
      • 5.2.1 pom文件添加actuator依赖
      • 5.2.2 启动类
    • 5.3 访问监控页面

易于理解笔记:https://www.cnblogs.com/yawen/p/6655352.html

详细概念流程:https://blog.csdn.net/loushuiyifan/article/details/82702522

1. Hystrix理解

1.1 概述

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

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

Hystrix作用:

  • 服务降级
  • 服务熔断
  • 服务限流
  • 实时监控

1.2 背景

分布式系统环境下,服务间类似依赖非常常见,一个业务调用通常依赖多个基础服务。如下图,对于同步调用,当库存服务不可用时,商品服务请求线程被阻塞,当有大批量请求调用库存服务时,最终可能导致整个商品服务资源耗尽,无法继续对外提供服务。并且这种不可用可能沿请求调用链向上传递,这种现象被称为雪崩效应。

1.3 雪崩效应常见场景

  • 硬件故障:如服务器宕机,机房断电,光纤被挖断等。
  • 流量激增:如异常流量,重试加大流量等。
  • 缓存穿透:一般发生在应用重启,所有缓存失效时,以及短时间内大量缓存失效时。大量的缓存不命中,使请求直击后端服务,造成服务提供者超负荷运行,引起服务不可用。
  • 程序BUG:如程序逻辑导致内存泄漏,JVM长时间FullGC等。
  • 同步等待:服务间采用同步调用模式,同步等待造成的资源耗尽。

1.4 雪崩效应应对策略

针对造成雪崩效应的不同场景,可以使用不同的应对策略,没有一种通用所有场景的策略,参考如下:

  • 硬件故障:多机房容灾、异地多活等。
  • 流量激增:服务自动扩容、流量控制(限流、关闭重试)等。
  • 缓存穿透:缓存预加载、缓存异步加载等。
  • 程序BUG:修改程序bug、及时释放资源等。
  • 同步等待:资源隔离、MQ解耦、不可用服务调用快速失败等。资源隔离通常指不同服务调用采用不同的线程池;不可用服务调用快速失败一般通过熔断器模式结合超时机制实现。

综上所述,如果一个应用不能对来自依赖的故障进行隔离,那该应用本身就处在被拖垮的风险中。 因此,为了构建稳定、可靠的分布式系统,我们的服务应当具有自我保护能力,当依赖服务不可用时,当前服务启动自我保护功能,从而避免发生雪崩效应。本文将重点介绍使用Hystrix解决同步等待的雪崩问题。

1.5 初探Hystrix

Hystrix [hɪst’rɪks],中文含义是豪猪,因其背上长满棘刺,从而拥有了自我保护的能力。本文所说的Hystrix是Netflix开源的一款容错框架,同样具有自我保护能力。为了实现容错和自我保护,下面我们看看Hystrix如何设计和实现的。

Hystrix设计目标:

  • 对来自依赖的延迟和故障进行防护和控制——这些- - 依赖通常都是通过网络访问的
  • 阻止故障的连锁反应
  • 快速失败并迅速恢复
  • 回退并优雅降级
  • 提供近实时的监控与告警

Hystrix遵循的设计原则:

  • 防止任何单独的依赖耗尽资源(线程)
  • 过载立即切断并快速失败,防止排队
  • 尽可能提供回退以保护用户免受故障
  • 使用隔离技术(例如隔板,泳道和断路器模式)来限制任何一个依赖的影响
  • 通过近实时的指标,监控和告警,确保故障被及时发现
  • 通过动态修改配置属性,确保故障及时恢复
  • 防止整个依赖客户端执行失败,而不仅仅是网络通信

Hystrix如何实现这些设计目标?

  • 使用命令模式将所有对外部服务(或依赖关系)的调用包装在HystrixCommand或HystrixObservableCommand对象中,并将该对象放在单独的线程中执行;
  • 每个依赖都维护着一个线程池(或信号量),线程池被耗尽则拒绝请求(而不是让请求排队)。
  • 记录请求成功,失败,超时和线程拒绝。
  • 服务错误百分比超过了阈值,熔断器开关自动打开,一段时间内停止对该服务的所有请求。
  • 请求失败,被拒绝,超时或熔断时执行降级逻辑。
  • 近实时地监控指标和配置的修改。

1.6 Hystrix流程图


2. 构建问题项目

2.2 构建cloud-provider-hystrix-payment8007项目

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

2.2.2 yml文件

server:port: 8007spring:application:name: cloud-provider-hystrix-paymenteureka:client:register-with-eureka: truefetch-registry: trueservice-url:defaultZone: http://eureka7001.com:7001/eureka

2.2.3 启动类

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

2.2.4 控制器

package com.springcloud.controller;import org.omg.CORBA.TIMEOUT;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.concurrent.TimeUnit;@RestController
public class PaymentController {@GetMapping("payment/hystrix/ok")public String ok(){return "线程池:"+Thread.currentThread().getName()+",信息:OK";}@GetMapping("payment/hystrix/timeout")public String timeout(){long timeout=3000;try {Thread.sleep(timeout);} catch (InterruptedException e) {e.printStackTrace();}return "线程池:"+Thread.currentThread().getName()+",信息:TIMEOUT ";}
}

2.2.5 普通测试

  1. 启动7001
  2. 启动8007
  3. 访问http://localhost:8007/payment/hystrix/ok
  4. 访问http://localhost:8007/payment/hystrix/timeout

2.2.6 高并发测试

  1. 对http://localhost:8007/payment/hystrix/ok进行高并发
  2. 访问ok页面(卡顿)
  3. 访问timeout页面(卡顿)

两个页面都卡顿的原因是并发量超过了Tomcat的工作线程数,没有多余的线程来分解压力和处理。



2.3 构建cloud-consumer-hystrix-order6007项目

2.3.1 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.springcloud</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>cloud-consumer-hystrix-order6007</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-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><!-- 引入自己定义的api通用包,可以使用Payment支付Entity --><groupId>com.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>

2.3.2 yml文件

server:port: 6007spring:application:name: cloud-consumer-hystrix-ordereureka:client:register-with-eureka: falsefetch-registry: trueservice-url:defaultZone: http://eureka7001.com:7001/eureka

2.3.3 启动类

package com.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;@SpringBootApplication
@EnableFeignClients
public class OrderHystrixMain6007 {public static void main(String[] args) {SpringApplication.run(OrderHystrixMain6007.class,args);}
}

2.3.4 Feign的Service接口

package com.springcloud.service;import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;@Component
@FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT")
public interface PaymentFeignService {@GetMapping("/payment/hystrix/ok")public String ok();@GetMapping("/payment/hystrix/timeout")public String timeout();
}

2.3.5 控制器

package com.springcloud.controller;import com.springcloud.service.PaymentFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class OrderController {@AutowiredPaymentFeignService paymentFeignService;@GetMapping("/consumer/payment/hystrix/ok")public String ok(){return paymentFeignService.ok();}@GetMapping("/consumer/payment/hystrix/timeout")public String timeout(){return paymentFeignService.timeout();}
}

2.3.6 普通测试

  1. 启动7001
  2. 启动8007
  3. 启动6007
  4. 访问http://localhost:6007/consumer/payment/hystrix/ok
  5. 访问http://localhost:6007/consumer/payment/hystrix/timeout

3.2.7 对8007高并发测试

继续对8007高并发测试,因为6007调用了8007的服务,但是8007因为被大量并发卡住了,导致6007也卡住了,最终导致用户体验不好


3 服务降级

3.1 概述

当服务出现异常状况时不让客户端等待并立刻返回一个友好提示fallback

哪些情况会触发降级

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

以8007和6007作为例子

  • 对方服务(8007)超时或down机了,调用者(6007)不能一直卡死等待,必须有服务降级
  • 对方服务(8007)OK,调用者(6007)自己出故障或有自我要求(自己的等待时间小于服务提供者),自己处理降级

3.2 服务提供者8007服务降级(超时)

3.2.1 启动类

增加@EnableCircuitBreaker或@EnableHystrix注解,@EnableHystrix继承扩展了@EnableCircuitBreaker的功能

package com.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;@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
public class PaymentHystrixMain8007 {public static void main(String[] args) {SpringApplication.run(PaymentHystrixMain8007.class,args);}
}

3.2.2 控制器类

使用@HystrixCommand注解添加到需要服务降级的方法上

package com.springcloud.controller;import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.omg.CORBA.TIMEOUT;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.concurrent.TimeUnit;@RestController
@Slf4j
public class PaymentController {@GetMapping("/payment/hystrix/ok")public String ok(){String result="线程池:"+Thread.currentThread().getName()+",信息:OK";log.info(result);return result;}// fallbackMethod是当timeout()出错或超时时调用timeout_handler()进行处理响应给调用者@HystrixCommand(fallbackMethod = "timeout_handler",commandProperties ={// execution.isolation.thread.timeoutInMilliseconds表示timeout()执行超过指定时间则触发服务降级// 因为6007的Feign默认只会等待1秒,所以这里设置900毫秒,有足够时间把timeout_handler()响应给6007@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "900")})@GetMapping("/payment/hystrix/timeout")public String timeout(){long timeout=3000;try {Thread.sleep(timeout);} catch (InterruptedException e) {e.printStackTrace();}String result="线程池:"+Thread.currentThread().getName()+",信息:TIMEOUT";log.info(result);return result;}public String timeout_handler(){String result="线程池:"+Thread.currentThread().getName()+",信息:调用8007支付接口超时或异常 ";return result;}
}

3.2.3 测试

  1. 启动7001
  2. 启动8007
  3. 启动6007
  4. 注意:修改@HystrixCommand中的属性需要重启服务,自动部署devtools不一定生效
  5. 访问http://localhost:6007/consumer/payment/hystrix/timeout

3.3 服务消费者6007服务降级(异常)

3.3.1 启动类

增加@EnableCircuitBreaker或@EnableHystrix注解,@EnableHystrix继承扩展了@EnableCircuitBreaker的功能

package com.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.netflix.hystrix.EnableHystrix;@SpringBootApplication
@EnableEurekaClient
@EnableHystrix
public class PaymentHystrixMain8007 {public static void main(String[] args) {SpringApplication.run(PaymentHystrixMain8007.class,args);}
}

3.3.2 控制器

package com.springcloud.controller;import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.springcloud.service.PaymentFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class OrderController {@AutowiredPaymentFeignService paymentFeignService;@HystrixCommand(fallbackMethod = "ok_handler")@GetMapping("/consumer/payment/hystrix/ok")public String ok(){int num=10/0;return paymentFeignService.ok();}public String ok_handler(){return "6007出错了,请联系管理员";}@GetMapping("/consumer/payment/hystrix/timeout")public String timeout(){return paymentFeignService.timeout();}
}

3.3.3 测试

  1. 启动7001
  2. 启动8007
  3. 启动6007
  4. 注意:修改@HystrixCommand中的属性需要重启服务,自动部署devtools不一定生效
  5. 访问http://localhost:6007/consumer/payment/hystrix/ok

3.4 简化代码结构

3.4.1 默认Fallback方法

package com.springcloud.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.springcloud.service.PaymentFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
// 指定默认的Fallback方法
@DefaultProperties(defaultFallback = "default_handler")
public class OrderController {@AutowiredPaymentFeignService paymentFeignService;// 默认Fallback必须是无参的public String default_handler(){return "8007系统down机啦啦啦啦啦啦啦啦啦";}@HystrixCommand(fallbackMethod = "ok_handler")@GetMapping("/consumer/payment/hystrix/ok")public String ok(){int num=10/0;return paymentFeignService.ok();}public String ok_handler(){return "6007出错了,请联系管理员";}// @HystrixCommand如果没有设置fallbackMethod属性,则会自动使用默认Fallback@HystrixCommand  @GetMapping("/consumer/payment/hystrix/timeout")public String timeout(){return paymentFeignService.timeout();}
}

启动7001
启动6007
不要启动8007
访问http://localhost:6007/consumer/payment/hystrix/ok
访问http://localhost:6007/consumer/payment/hystrix/timeout

3.4.2 OpenFeign与Hystrix合用

  • yml文件
server:port: 6007spring:application:name: cloud-consumer-hystrix-ordereureka:client:register-with-eureka: falsefetch-registry: trueservice-url:defaultZone: http://eureka7001.com:7001/eureka# OpenFeign与Hystrix何用,需要添加以下代码
feign:hystrix:enabled: true
  • 启动类
package com.springcloud;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.openfeign.EnableFeignClients;@SpringBootApplication
@EnableFeignClients  // 开启OpenFeign支持
@EnableHystrix       // 开启Hystrix支持
public class OrderHystrixMain6007 {public static void main(String[] args) {SpringApplication.run(OrderHystrixMain6007.class,args);}
}
  • Feign服务接口

设置@FeignClient的fallback属性

package com.springcloud.service;import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;@Component
// 在@FeignClient注解的fallback属性是为当前调用远程服务的Feign接口进行服务降级Fallback处理的类
@FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT",fallback = PaymentFallbackService.class)
public interface PaymentFeignService {@GetMapping("/payment/hystrix/ok")public String ok();@GetMapping("/payment/hystrix/timeout")public String timeout();
}
  • Fallback处理类
package com.springcloud.service;import org.springframework.stereotype.Component;@Component  //记得加上@Component注解
// 实现Feign服务的接口,为每个远程访问的方法设置Fallback
public class PaymentFallbackService implements  PaymentFeignService {@Overridepublic String ok() {return "8007的ok出错了";}@Overridepublic String timeout() {return "8007的timeout出错了";}}
  • 控制器

还原成原来的样子

package com.springcloud.controller;import com.springcloud.service.PaymentFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class OrderController {@AutowiredPaymentFeignService paymentFeignService;@GetMapping("/consumer/payment/hystrix/ok")public String ok(){return paymentFeignService.ok();}@GetMapping("/consumer/payment/hystrix/timeout")public String timeout(){return paymentFeignService.timeout();}
}
  • 测试

启动7001
启动6007
不要启动8007
访问http://localhost:6007/consumer/payment/hystrix/ok
访问http://localhost:6007/consumer/payment/hystrix/timeout

4. 服务熔断

4.1 概述

4.1.1 熔断器是什么

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

4.1.2 熔断器状态

闭合:不会对服务进行熔断,即不干活
断开:请求不再进行调用当前服务,直接fallback
半开:断开后每隔一段时间,尝试调用当前服务,根据规则改变熔断器状态

4.1.3 执行过程

  1. 当请求数满足一定的阀值的时候(默认10秒内超过20个请求次数)熔断器才会开始工作;如果请求数低于阀值,熔断器不会干活,即上面流程完全不执行。
  2. 熔断器一开始是闭合状态,如果一定时间内超过规定请求失败率(默认10秒内50%的失败率)熔断器就会断开;如果低于失败率则正常访问当前服务。
  3. 熔断器断开期间(默认5秒)所有请求直接进入fallback。
  4. 熔断器断开指定时间(默认5秒)后会进入半开状态,会让其中一个请求访问当前服务,如果成功则把熔断器闭合,如果失败则把熔断器断开。
  5. 根据熔断器状态重复以上步骤

4.2 案例演示

为了省事在8007新建一个HystrixController,直接在浏览器访问HystrixController中的方法,不再用6007调用8007的服务

4.2.1 HystrixController

package com.springcloud.controller;import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;@RestController
public class HystrixController {@HystrixCommand(fallbackMethod = "division_handler",commandProperties = {@HystrixProperty(name = "circuitBreaker.enabled",value = "true"),  //启用熔断器@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"), //快照时间窗@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "20"),  //在快照时间窗内请求总数阀值@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "50"),//在快照时间窗内请求失败百分比阀值})@GetMapping("/hystrix/division/{num}")public String division(@PathVariable("num") int num){int result=10/num;return "结果:"+result;}public String division_handler(@PathVariable("num") int num){return "出错啦,数字:"+num;}
}

4.2.2 测试

单次访问

过程:先10秒内错误访问5次,10秒后正确访问1次
结果:10秒后访问那一次正确显示结果
原因:10秒内访问5次,未达到让熔断器干活的程度

过程:先10秒内错误访问20次以上,第10秒正确访问1次,第15秒正确访问1次,第20秒正确访问1次
结果:10秒后访问那一次显示出错了,第15秒访问显示成功,第20秒访问成功
原因:10秒内访问超过20次,熔断器开始干活了,因为在这10秒内全是错误访问,失败率达到了100%,远超过规定的50%,所以熔断器断开了,断开 的期间(默认持续5秒),所有请求都是直接调用fallback,所以虽然是正确访问,但结果是错误的;熔断器断开5秒后进入半开状态,尝试恢复链路,对第15秒访问当前服务,访问成功了;第15秒访问成功会把熔断器从半开切换成闭合状态,所以第20秒也能正常访问(未到熔断器干活次数)

4.2.3 熔断器全部配置

//========================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";
}

5. 服务监控HystrixDashboard

5.1 新建cloud-hystrix-dashboard9001模块

5.1.1 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.springcloud</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>cloud-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.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.1.2 yml文件

server:port: 9001

5.1.3 启动类

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

5.2 修改被监控项目cloud-provider-hystrix-payment8007

5.2.1 pom文件添加actuator依赖

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

5.2.2 启动类

package com.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.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.context.annotation.Bean;@SpringBootApplication
@EnableEurekaClient
@EnableHystrix
public class PaymentHystrixMain8007 {public static void main(String[] args) {SpringApplication.run(PaymentHystrixMain8007.class,args);}/***此配置是为了服务监控而配置,与服务容错本身无关,springcloud升级后的坑*ServletRegistrationBean因为springboot的默认路径不是"/hystrix.stream",*只要在自己的项目里配置上下面的servlet就可以了*/@Beanpublic ServletRegistrationBean getServlet() {HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);registrationBean.setLoadOnStartup(1);registrationBean.addUrlMappings("/hystrix.stream");registrationBean.setName("HystrixMetricsStreamServlet");return registrationBean;}}

5.3 访问监控页面

【SpringCloud】Hystrix断路器【五】相关推荐

  1. 五、Hystrix断路器

    Hystrix断路器 概述 分布式系统面临的问题 复杂分布式体系结构中的应用程序有数十个依赖关系,每一个依赖关系在某些时候将不可避免的失败. 服务雪崩 多个微服务之间调用的时候,假如微服务A调用微服务 ...

  2. Dubbo(十五)springboot工程dubbo整合SpringCloud Hystrix

    本章将编写一个使用SpringBoot工程集成dubbo使用hystrix组件实现服务熔断示例.包含服务提供者工程和服务消费者工程.主要在实现整合springcloud hystrix过程步骤如下: ...

  3. SpringCloud中 Feign结合Hystrix断路器开发。

    Feign结合Hystrix断路器开发: 转载于:https://www.cnblogs.com/longdb/p/10468371.html

  4. 深入了解SpringCloud Hystrix

    雪崩效应即在多个服务节点当中,如果有一个服务不可用而这个不可用的服务导致整个应用资源都耗在这里,进而影响整个系统的崩溃.在分布式环境中,不可避免地会出现雪崩效应.Hystrix是一个netflix实现 ...

  5. SpringCloud Hystrix熔断器

    SpringCloud Hystrix熔断器 15.Hystrix熔断器:简介及作用 目标:理解Hystrix的作用 介绍:Hystrix,英文意思是豪猪,全身是刺,看起来就不好惹,是一种保护机制. ...

  6. SpringCloud实战(五)-路由网关(zuul)

    本文是SpringCloud实战(五)-路由网关(zuul),若要关注前文,请点击传送门: SpringCloud实战(四)-断路器(Hystrix) 前文我们介绍了Hystrix断路器.在平常工作中 ...

  7. 史上最简单的SpringCloud教程 | 第五篇: 路由网关(zuul)

    转:https://blog.csdn.net/forezp/article/details/69939114 最新版本: 史上最简单的SpringCloud教程 | 第五篇: 路由网关(zuul)( ...

  8. springcloud Feign断路器实战和问题总结

    springcloud Feign断路器实战和问题总结 断路由是防止该服务调用其他外服务时,外服务宕机或者出差时,影响到本服务的宕机,引起大面积的瘫痪,所以才有了断路由的由来. springcloud ...

  9. springcloud gateway断路器抛的错default failed and fallback disabled

    有没有springcloud的大神碰到这个问题? 这是springcloud gateway断路器抛的错 default failed and fallback disabled., httpStat ...

  10. Hystrix断路器原理及实现(服务降级、熔断、限流)

    Hystrix断路器原理及实现(服务降级.熔断.限流) 分布式系统面临的问题 Hystrix重要概念(面试常考) Hystrix案例 Hystrix 服务提供者 Hystrix 服务消费者 原因与解决 ...

最新文章

  1. windows安装配置git和Tortoisegit
  2. 预处理_气体在线分析仪预处理系统的工作内容
  3. EduCoder Linux之文件/目录搜索
  4. 腾讯DCI上线基于集中控制的SR-TE方案
  5. js判断字符是否为空的方法
  6. 使用 ESXCLI 命令从主机移除设备
  7. python为什么那么多人点赞_python为何会火遍全球?它究竟是什么呢?阿里大佬告诉你答案...
  8. Windows Mobile 获取来电号码和屏蔽来电
  9. 27.MySQL Status
  10. android串口wifi模块,一文深度了解串口WiFi模块的应用场景
  11. 在JavaScript中创建SVG矢量图EAN13条码
  12. @RunWith和@ContextConfiguration的用法
  13. 什么表单设计工具能快速提升办公效率?
  14. 使用python爬取12306上面所有车次数据
  15. 阿里云漏洞敏捷管理自动化报告
  16. 如何独立设置Mac触摸板方向和鼠标滚轮方向?
  17. midi键盘接电脑实现电子琴功能
  18. Java燕山大学_GitHub - jiajiayao/YsuSelfStudy: 燕山大学空教室查询及教务辅助系统,中国大学生计算机设计大赛省赛三等奖,已上架小米应用商店...
  19. 围城下的物业与业主的困兽之斗
  20. zip压缩解压缩开源库-LiteZip

热门文章

  1. word压缩文件大小不变怎么办?3个压缩技巧教给你
  2. 大一新生如何选电脑?专业不同,需求不同
  3. Ubuntu root切换
  4. html页面点击按钮实现页面跳转
  5. iOS TableView显示出现:Warning once only: Detected a case where constraints ambiguously suggest a height
  6. 关于RikiRobot ROS机器人的介绍
  7. web前端--用div替代frameset和frame
  8. VMware无法打开克隆的虚拟机
  9. app提交上架最新流程 ios
  10. 三星s7 android8.0,不抛弃不放弃:三星正为S7系列打造Android 8.0