【问题标题】:Hystrix class per command?每个命令的 Hystrix 类?
【发布时间】:2018-09-12 13:35:59
【问题描述】:

我的应用有一组可配置的(在运行时)要调用的外部端点:

/foo
/bar

并用于使用 apache HttpClient 进行 http 调用。

我想在这里使用 Hystrix 包装 HttpClient,但我想为每个端点分离断路器,这样如果一个失败,它不会影响另一个。

我可以通过开设 2 个班级来做到这一点:

FooCommand extends HystrixCommand<...> {
}

BarCommand extends HystrixCommand<...> {
}

但这是一个硬编码的解决方案,阻止我在运行时动态配置它。

我如何构造一个单一的 hystrix 命令类来实现这一点?

最好是这样的:

class MyHystrixHttpClient extends HystrixCommand<Data> {
    public MyHystrixHttpClient(String endpoint) {
        // here somehow tell hystrix to use "endpoint" string getHash() as a grouping key
    }
}

那么我可以这样使用它:

new MyHystrixHttpClient("/foo").execute(); // (1)
new MyHystrixHttpClient("/bar").execute(); // (2)

如果 (1) 失败,(2) 仍将被单独执行和处理

【问题讨论】:

    标签: java hystrix


    【解决方案1】:

    您可以在构造函数中设置命令键。像这样的。

    public class HttpCommand extends HystrixCommand<HttpResponse> {
    
      private final HttpClient httpClient;
      private final HttpRequestBase request;
    
      public HttpCommand(String commandKey, HttpClient httpClient, HttpRequestBase request) {
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("HttpGroup"))
            .andCommandKey(HystrixCommandKey.Factory.asKey(commandKey)));
        this.httpClient = httpClient;
        this.request = request;
      }
    
      @Override
      protected HttpResponse run() throws Exception {
        return httpClient.execute(request);
      }
    
    }
    

    【讨论】:

    猜你喜欢
    • 2018-07-15
    • 2019-01-21
    • 2015-03-16
    • 2018-08-01
    • 2020-11-06
    • 2017-02-20
    • 2015-09-25
    • 2017-03-30
    • 1970-01-01
    相关资源
    最近更新 更多