Netflix实现了一个断路器模式的类库叫作Hystrix。 在一个微服务架构中一般来讲会有一个多层服务的调用。java
Figure 1. Microservice Graphgit
对于用户来讲,一个底层服务失败,就会引起一系列的连锁反应。当调用一个服务达到一个阈值(Hystrix默认是5秒内20次失败),断路器打开,并拒绝调用。开发者能够指定一些特定错误,来触发降级操做。github
Figure 2. Hystrix fallback prevents cascading failuresweb
断路器打开后,阻止了连锁反应而且容许丢弃或者等待服务从新响应。降级调用是Hystrix提供的另外一种策略,好比提供一个静态数据或者一个合理的空值。 降级也能够链式触发,好比,一个服务降级可能引发另一些业务调用获得一个降级的静态数据。spring
在工程中引入Hystrix只须要使用特定的starter就能够了。如:group:
org.springframework.cloud
,artifact id :spring-cloud-starter-hystrix
。如何使用Spring Cloud构建系统能够参见 Spring Cloud Project page安全
例如:架构
@SpringBootApplication @EnableCircuitBreaker public class Application { public static void main(String[] args) { new SpringApplicationBuilder(Application.class).web(true).run(args); } } @Component public class StoreIntegration { @HystrixCommand(fallbackMethod = "defaultStores") public Object getStores(Map<String, Object> parameters) { //do stuff that might fail } public Object defaultStores(Map<String, Object> parameters) { return /* something useful */; } }
@HystrixCommand
是由Netfix开源的javanica提供的。并发
Spring Cloud 经过这个注解自动包装了一个代理去关联Hystrix断路器。 断路器提供对调用链路的断开和闭合控制,主要用于调用失败处理。spring-boot
能够经过配置
@HystrixCommand
的commandProperties
属性来列出一些列的@HystrixProperty
,来对Hystrix断路器进行配置。详情见此处。详细的属性配置项说明能够参见Hystrix的Wiki。微服务
若是你想要让一些本地线程上下文传播到
@HystrixCommand
中,那么默认状况下是不行的,由于Hystrix是在一个普通的线程池中执行的。
你能够二选一来达到传播上下文的目的,要么配置Hystrix,让其使用同一个线程去处理调用;要么,干脆直接在注解中使用一个不一样的隔离策略。例如:
@HystrixCommand(fallbackMethod = "stubMyService", commandProperties = { @HystrixProperty(name="execution.isolation.strategy", value="SEMAPHORE") } ) ...
一样的,若是你使用过
@SessionScope
或者@RequestScope
。你就会知道你这样作是由于,运行时异常会找不到做用域的上下文。
你还能够配置
hystrix.shareSecurityContext
为true
。这样作,将会让Hystris自动配置一个并发策略插件,当使用Hystris命令从主线程迁移SecurityContext
时自动同步。Hystris不容许多个并发策略同时存在,因此须要本身扩展一个HystrixConcurrencyStrategy
注册到Spring中。Spring Cloud会自动在Spring上下文中发现你的实现类,并自动包装成一个自定义Hystrix插件。
断路器的状态也能够经过
/health
接口被应用查看到。
{ "hystrix": { "openCircuitBreakers": [ "StoreIntegration::getStoresByLocationLink" ], "status": "CIRCUIT_OPEN" }, "status": "UP" }
开启流量测量须要引入依赖:
spring-boot-starter-actuator
。将会提供一个/hystrix.stream
管理接口。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>