介绍
Netflix通过Hystrix库实现了断路器模式,在微服务架构体系中存在多层调用的,低级的服务故障可能会导致级联故障,断路器可以有效保护微服务,防止出现雪崩效应。
断路器开启的条件
- 在定义的时间窗口内,默认10s(metrics.rollingStats.timeInMilliseconds)
- 某服务被请求次数超过阈值,默认20次(circuitBreaker.requestVolumeThreshold)
- 调用失败率大于阈值,默认>50%(circuitBreaker.errorThresholdPercentage)
基于@HystrixCommand注解的断开器实例
- 简单应用
@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注解的方法中,是不能正常运行的,因为默认是线程隔离的,只能操作同一个线程的上下文信息。包括类加了 @SessionScope or @RequestScope注解也是一样的。
@HystrixCommand(fallbackMethod = "stubMyService",
commandProperties = {
@HystrixProperty(name="execution.isolation.strategy", value="SEMAPHORE")
}
)
你可以通过配置如下参数,Hystrix会自动将上下文传递给@HystrixCommand注解的方法中。
hystrix.shareSecurityContext=true
断路器状态查看
可以通过健康端点来查看断路器状态,端点路径/actuator/health或/health,内容如下:
{
"hystrix": {
"openCircuitBreakers": [
"StoreIntegration::getStoresByLocationLink"
],
"status": "CIRCUIT_OPEN"
},
"status": "UP"
}
开启断路器度量流
- 依赖:spring-boot-starter-actuator
- 配置:management.endpoints.web.exposure.include: hystrix.stream
- 访问:/actuator/hystrix.stream