13. 断路器:Hystrix Clients

Netflix 创建了一个名为Hystrix的 library,它实现了断路器 pattern。在微服务 architecture 中,拥有多层服务 calls 是常见的。

图 1_.微服务图

Hystrix

较低级别服务中的服务故障可能导致级联故障一直到用户。 calls 到特定服务大于circuitBreaker.requestVolumeThreshold(默认值:20 个请求)且故障百分比大于circuitBreaker.errorThresholdPercentage(默认值:> 50%)在由metrics.rollingStats.timeInMilliseconds定义的滚动窗口中(默认值:10 秒),电路打开并且呼叫没有。在出现错误和开路的情况下,开发人员可以提供后备。

图 1_.Hystrix 后备防止级联故障

HystrixFallback

有一个开放的电路可以阻止级联故障,并允许不堪重负或失败的服务 time 来治愈。回退可以是另一个 Hystrix 保护调用,静态数据或理智的空 value。回退可能会被链接,因此第一个回退会使一些其他业务调用反过来又回到静态数据。

13.1 如何包含 Hystrix

要在项目中包含 Hystrix,请使用带有 group org.springframework.cloud和 artifact id spring-cloud-starter-netflix-hystrix的 starter。有关使用当前 Spring Cloud Release Train 设置 build 系统的详细信息,请参阅Spring Cloud 项目页面

Example boot app:

@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 Scopes

如果您希望某些线程 local context 传播到@HystrixCommand,则默认声明将不起作用,因为它在线程池中执行该命令(如果超时)。您可以使用某些 configuration 切换 Hystrix 以使用与调用者相同的线程,或者通过要求它使用不同的“隔离策略”来直接在 annotation 中。例如:

@HystrixCommand(fallbackMethod = "stubMyService",
    commandProperties = {
      @HystrixProperty(name="execution.isolation.strategy", value="SEMAPHORE")
    }
)
...

如果您使用@SessionScope@RequestScope,则同样适用。您将知道何时需要执行此操作,因为运行时 exception 表示无法找到作用域 context。

您还可以选择将hystrix.shareSecurityContext property 设置为true。这样做会自动配置 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的依赖关系。这会将/hystrix.stream公开为 management 端点。

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