# Hystrix 设计与实现

## Hystrix 设计目的

* 在通过第三方客户端来访问依赖（通常是经过网络请求）时，提供对延迟与故障的保护和控制；
* 在复杂的分布式系统中，停止故障的级联扩散；
* 支持快速失败和快速恢复；
* 可以支持回退（Fallback）逻辑和优雅降级；
* 支持接近实时的监控、报警和操作控制。

## Hystrix 设计原则

* 避免任意依赖（依赖是指：当前应用对外部服务的调用）耗尽容器（例如 Tomcat）的用户线程；
* 减少应用的负载，使用快速失败模式，而不是队列等待模式；
* 在必要的情况下提供回退方案，用于保护应用免受故障影响；
* 使用隔离技术来限制任意依赖所带来的不良影响；
* 优化故障的发现时间，通过接近实时的数据指标、监控和报警等；
* 优化故障的恢复时间；
* 在整个依赖的客户端范围中，而不仅是在网络通讯中，保护应用免受故障影响。

## Hystrix 实现原理

* 将所有对外部系统的调用（即依赖）封装成 `HystrixCommand` 或者 `HystrixObservableCommand` 对象，它们通常是运行在一个单独的线程中；
* 大于预定义阈值的调用超时时间；
* 对每个依赖会维护一个小的线程池（或者 `semaphore`）。当线程池（或者 `semaphore`）已满时，发送给该依赖的请求会被立即拒绝，而不是进入队列再等待；
* 收集调用结果的各种指标：成功、失败（抛出异常）、超时、拒绝；
* 如果某个服务的调用错误率超过了一定阈值，则会使熔断器跳闸，并在一段时间内停止对该特定服务的所有请求；
* 当请求失败时、被拒绝时、超时时，或者熔断器跳闸时，执行调用请求的回退逻辑；
* 接近实时的监控指标采集和配置更新操作。

## 参考资料

* [Hystrix Home](https://github.com/Netflix/Hystrix/wiki)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gitbook.fantasticmao.cn/tech/java/qi-ta/hystrix-she-ji-yu-shi-xian.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
