13. 断路器:Hystrix Clients
Netflix 创建了一个名为Hystrix的 library,它实现了断路器 pattern。在微服务 architecture 中,有多个服务 calls 层是 common,如下面的示例所示:
图 1_.微服务图
较低级别服务中的服务故障可能导致级联故障一直到用户。 calls 到特定服务超过circuitBreaker.requestVolumeThreshold
(默认值:20 个请求)且故障百分比大于circuitBreaker.errorThresholdPercentage
(默认值:> 50%)在metrics.rollingStats.timeInMilliseconds
定义的滚动窗口中(默认值:10 秒),电路打开,呼叫为没有。在出现错误和开路的情况下,开发人员可以提供回退。
图 1_.Hystrix 后备防止级联故障
开放式电路可以阻止级联故障,并且可以使服务不堪重负或无法恢复。回退可以是另一个 Hystrix 保护调用,静态数据或合理的空 value。可以链接回退,以便第一个回退进行其他业务调用,这反过来又回到静态数据。
13.1 如何包含 Hystrix
要在项目中包含 Hystrix,请使用 group ID 为org.springframework.cloud
且 artifact ID 为spring-cloud-starter-netflix-hystrix
的 starter。有关使用当前 Spring Cloud Release Train 设置 build 系统的详细信息,请参阅Spring Cloud 项目页面。
以下 example 显示了一个带有 Hystrix 断路器的最小 Eureka 服务器:
@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
由名为“爪哇”的 Netflix contrib library 提供。 Spring Cloud 在连接到 Hystrix 断路器的代理中自动将 Spring beans 与注释包装在一起。断路器计算何时打开和关闭电路以及在发生故障时应采取的措施。
要配置@HystrixCommand
,您可以将commandProperties
属性与@HystrixProperty
注释列表一起使用。有关详细信息,请参阅这里。有关 properties 的详细信息,请参阅Hystrix wiki。
13.2 传播安全性 Context 或使用 Spring 范围
如果您希望某些线程 local context 传播到@HystrixCommand
,则默认声明不起作用,因为它在线程池中执行该命令(如果超时)。您可以通过 configuration 切换 Hystrix 以使用与调用者相同的线程,或者通过要求它使用不同的“隔离策略”来直接在 annotation 中。以下 example 演示了在 annotation 中设置线程:
@HystrixCommand(fallbackMethod = "stubMyService",
commandProperties = {
@HystrixProperty(name="execution.isolation.strategy", value="SEMAPHORE")
}
)
...
如果您使用@SessionScope
或@RequestScope
,则同样适用。如果遇到运行时 exception,表示无法找到作用域 context,则需要使用相同的线程。
您还可以选择将hystrix.shareSecurityContext
property 设置为true
。这样做 auto-configures Hystrix 并发策略插件 hook 将SecurityContext
从主线程传输到 Hystrix 命令使用的那个。 Hystrix 不会注册多个 Hystrix 并发策略,因此可以通过将自己的HystrixConcurrencyStrategy
声明为 Spring bean 来获得扩展机制。 Spring Cloud 在 Spring context 中查找 implementation 并将其包装在自己的插件中。
13.3 健康指标
连接断路器的 state 也暴露在调用 application 的/health
端点中,如下面的示例所示:
{
"hystrix": {
"openCircuitBreakers": [
"StoreIntegration::getStoresByLocationLink"
],
"status": "CIRCUIT_OPEN"
},
"status": "UP"
}
13.4 Hystrix Metrics Stream
要启用 Hystrix metrics 流,请在spring-boot-starter-actuator
上包含依赖项并设置management.endpoints.web.exposure.include: hystrix.stream
。这样做会将/actuator/hystrix.stream
公开为 management 端点,如下面的示例所示:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>