soul入门 第十五章 hystrix熔断器插件原理

292 阅读2分钟

soul入门 第十五章 hystrix熔断器插件原理

介绍


​ 一个分布式系统通常由许多相互依赖的服务所组成的,由于服务多,某个服务出现故障的几率相对会增高,这些服务相互调用,当某些被依赖的服务出现故障或响应延迟的问题时候,调用该服务的服务可能会出现资源耗尽等问题,在最坏的情况下,整个应用程序将崩溃。

​ Hystrix框架通过提供熔断降级来控制服务之间的交互依赖,通过隔离故障服务并停止故障的级联,以避免故障扩大化。

Hystrix 的功能作用


  • 快速失败,迅速恢复。

  • 降级

  • 停止复杂分布式系统级联故障

soul如何引入hystrix插件


1、admin后台开启hystrix插件

2、给hystrix添加选择器及规则

配置哪些请求会被hystrix处理。那如何处理呢?通过规则告诉hystrix怎么处理。

3、看下关键的代码

@Override
protected Mono<Void> doExecute(final ServerWebExchange exchange, final SoulPluginChain chain, final SelectorData selector, final RuleData rule) {
    final SoulContext soulContext = exchange.getAttribute(Constants.CONTEXT);
    assert soulContext != null;
  // 封装了断路器的规则
    final HystrixHandle hystrixHandle = GsonUtils.getInstance().fromJson(rule.getHandle(), HystrixHandle.class);
   // 生成command
    Command command = fetchCommand(hystrixHandle, exchange, chain);
    return Mono.create(s -> {
        Subscription sub = command.fetchObservable().subscribe(s::success,
                s::error, s::success);
        s.onCancel(sub::unsubscribe);
        if (command.isCircuitBreakerOpen()) {
            log.error("hystrix execute have circuitBreaker is Open! groupKey:{},commandKey:{}", hystrixHandle.getGroupKey(), hystrixHandle.getCommandKey());
        }
    }).doOnError(throwable -> {
        log.error("hystrix execute exception:", throwable);
        exchange.getAttributes().put(Constants.CLIENT_RESPONSE_RESULT_TYPE, ResultEnum.ERROR.getName());
        chain.execute(exchange);
    }).then();
}

4、快速失败测试

在被访问的方法加上 Thread.sleep(1000*5); 休眠5秒

访问 http://localhost:9195/springcloud/order/findById?id=95

前几次都等了大概五秒才失败,后面访问就迅速失败了

{

​ "code": 500,

​ "message": "Internal Server Error",

​ "data": "/order/findById short-circuited and fallback failed."

}

小结

要能深刻理解hystrix插件的来龙去脉,首先🉐️了解hystrix的作用以及使用场景,了解参数的配置。