On this page
13. 断路器:HystrixClient
Netflix 创建了一个名为Hystrix的库,该库实现了断路器模式。在微服务架构中,通常有多个服务调用层,如以下示例所示:
图 13.1. 微服务图
较低级别的服务中的服务故障可能会导致级联故障,直至用户。当在metrics.rollingStats.timeInMilliseconds
定义的滚动窗口(默认值:10 秒)中,对特定服务的调用超过circuitBreaker.requestVolumeThreshold
(默认值:20 个请求)并且失败百分比大于circuitBreaker.errorThresholdPercentage
(默认值:> 50%)时,电路断开,且调用为没有发。在出现错误和断路的情况下,开发人员可以提供备用功能。
图 13.2 Hystrix 后备可防止级联故障
开路可停止级联故障,并让不堪重负的服务时间得以恢复。回退可以是另一个受 Hystrix 保护的调用,静态数据或合理的空值。可以将回退链接在一起,以便第一个回退进行其他业务调用,然后回退到静态数据。
13.1 如何包括 Hystrix
要将 Hystrix 包含在您的项目中,请使用组 ID 为org.springframework.cloud
且工件 ID 为spring-cloud-starter-netflix-hystrix
的启动程序。有关使用当前 Spring Cloud Release Train 设置构建系统的详细信息,请参见Spring Cloud Project 页面。
以下示例显示了带有 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
由名为"javanica"的 Netflix contrib 库提供。 Spring Cloud 会自动将带有该 Comments 的 Spring bean 包装在连接到 Hystrix 断路器的代理中。断路器计算何时断开和闭合电路,以及在发生故障时应采取的措施。
要配置@HystrixCommand
,可以将commandProperties
属性与@HystrixProperty
注解一起使用。有关更多详细信息,请参见here。有关可用属性的详细信息,请参见Hystrix wiki。
13.2 传播安全上下文或使用 Spring Scope
如果希望某些线程本地上下文传播到@HystrixCommand
,则默认声明不起作用,因为它在线程池中执行命令(如果超时)。您可以通过配置或要求 Comments 使用不同的“隔离策略”,将 Hystrix 切换为使用与调用方相同的线程或直接在 Comments 中使用。以下示例演示了如何在 Comments 中设置线程:
@HystrixCommand(fallbackMethod = "stubMyService",
commandProperties = {
@HystrixProperty(name="execution.isolation.strategy", value="SEMAPHORE")
}
)
...
如果您使用的是@SessionScope
或@RequestScope
,则同样适用。如果遇到运行时异常,提示它找不到范围内的上下文,则需要使用同一线程。
您还可以选择将hystrix.shareSecurityContext
属性设置为true
。这样做会自动配置一个 Hystrix 并发策略插件钩子,以将SecurityContext
从您的主线程转移到 Hystrix 命令使用的那个线程。 Hystrix 不允许注册多个 Hystrix 并发策略,因此可以通过将自己的HystrixConcurrencyStrategy
声明为 Spring bean 来使用扩展机制。 Spring Cloud 在 Spring 上下文中寻找您的实现,并将其包装在自己的插件中。
13.3 健康 Metrics
连接的断路器的状态也显示在调用应用程序的/health
端点中,如以下示例所示:
{
"hystrix": {
"openCircuitBreakers": [
"StoreIntegration::getStoresByLocationLink"
],
"status": "CIRCUIT_OPEN"
},
"status": "UP"
}
13.4 HystrixMetrics 流
要启用 HystrixMetrics 流,请包括对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>