1. 简介
Netflix has created a library called Hystrix that implements the circuit breaker pattern. In a microservice architecture it is common to have multiple layers of service calls.
A service failure in the lower level of services can cause cascading failure all the way up to the user. When calls to a particular service reach a certain threshold (20 failures in 5 seconds is the default in Hystrix), the circuit opens and the call is not made. In cases of error and an open circuit a fallback can be provided by the developer.
Having an open circuit stops cascading failures and allows overwhelmed or failing services time to heal. The fallback can be another Hystrix protected call, static data or a sane empty value. Fallbacks may be chained so the first fallback makes some other business call which in turn falls back to static data.
- Hystrix是netflix创建的一个用于服务降级、限流熔断的组件
- 微服务架构中一个服务调用链任何一个环节都有可能出现异常
- 若对异常没有合理的处理方式,则可能导致与此相关的功能不可用,甚至有可能引发雪崩现象
- Hystrix可以很好的解决服务不可用问题,可采用直接返回错误状态码、静态提示数据、以及转调统一处理方法等方式对调用方及时做出相应
2. 代码实现
2.1涉及的模块
- eureka-server-singleton:服务注册中心,端口8761
- eureka-service: 服务提供者,通过profile指定不同端口模拟一组微服务,端口8762、8763
- eureka-service-ribbon-hystrix:通过Ribbon调用服务提供者提供的服务,并提供限流熔断功能
2.2 源代码
2.2.1 Github地址
https://github.com/andyChenHuaYing/spring-cloud-demo
2.2.2 切换
通过tag切换git tag -d v1.0,若想修改,可根据此tag创建新的分支。
与Spring Cloud 之服务发现与调用-Ribbon#2.3 eureka-server-singleton 没有任何区别
2.3 eureka-service
2.4 eureka-service-ribbon-hystrix
2.4.1整体实现步骤
- pom.xml中引入
spring-cloud-starter-netflix-eureka-server
、spring-cloud-starter-netflix-ribbon
、spring-cloud-starter-netflix-hystrix
依赖 - application.yml中指定配置项:端口、application name、eureka-server地址
- SpringBoot 启动类添加注解
@EnableHystrix
开启使用Hystrix功能 - 使用
@Bean @LoadBalanced
向Spring容器注入org.springframework.web.client.RestTemplate
实例 - 在使用之处使用
@Autowired public RestTemplate restTemplate;
获取实例,调用服务提供方提供的方法 - 在需要使用Hystrix服务降级、容错功能的方法上使用
@HystrixCommand(fallbackMethod = "hiError")
指定回调方法
2.4.2 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>spring-cloud-finchley-demo</artifactId>
<groupId>org.oscar.scd</groupId>
<version>1.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<<