目录
较低级别的服务中的服务故障可能会导致级联故障,直至服务雪崩。在metrics.rollingStats.timeInMilliseconds定义的滚动窗口中,当对特定服务的调用超过circuitBreaker.requestVolumeThreshold(默认:20个请求)并且失败百分比大于circuitBreaker.errorThresholdPercentage(默认:> 50%)时(默认:10秒) ),则电路断开。在错误和断路的情况下,开发人员可以提供降级备用功能。

开路可停止级联故障,并让不堪重负的服务时间得以恢复。Fallback可以是另一个受Hystrix保护的可以访问的,静态数据或合理的空值。可以将回退链接在一起,以便第一个回退进行其他业务调用,然后回退到静态数据。
- <dependency>
- <groupId>org.springframework.cloudgroupId>
- <artifactId>spring-cloud-starter-netflix-hystrixartifactId>
- dependency>
- @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
parameters) { - //do stuff that might fail
- }
-
- public Object defaultStores(Map
parameters) { - return /* something useful */;
- }
- }
@HystrixCommand由一个名为“ javanica ”的Netflix contrib库提供。Spring Cloud将带有注释的Spring beans自动包装在与Hystrix断路器连接的代理中。断路器计算何时断开和闭合电路,以及在发生故障时应采取的措施。
要配置@HystrixCommand,可以将commandProperties属性与@HystrixProperty批注一起使用。
如果要将某些线程本地上下文传播到@HystrixCommand中,则默认声明无效,因为默认声明在线程池中执行命令(如果超时)。通过要求Hystrix使用不同的“ 隔离策略 ”,可以通过配置或直接在批注中切换Hystrix来使用与调用方相同的线程。下面的示例演示了如何在注释中设置线程:
- @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上下文中寻找实现,并将其包装在自己的插件中。
连接的断路器的状态也显示在调用应用程序的/health端点中,如以下示例所示:
- {
- "hystrix": {
- "openCircuitBreakers": [
- "StoreIntegration::getStoresByLocationLink"
- ],
- "status": "CIRCUIT_OPEN"
- },
- "status": "UP"
- }
当使用包裹Ribbon客户端的Hystrix命令时,要确保Hystrix超时配置为比配置的Ribbon超时更长,包括可能进行的任何重试。例如,如果Ribbon连接超时是一秒钟,并且Ribbon客户端可能重试了3次请求,则Hystrix超时应该稍微超过3秒。