我有一个hystrix断路器的实现,当测试时,我得到一个hystrix运行时异常,错误是电路断路器超时,回退失败。我需要增加断路器的超时时间吗?如果代码超时,它是否应该使断路器跳闸?
我的junit测试如下:

@Test
public void test4(){
    client = new DefaultHttpClient();
    httpget = new HttpGet("http://www.google.com:81");
    resp = new CircuitBreaker(client, "test4", httpget).execute();
    //assertEquals(HttpStatus.SC_GATEWAY_TIMEOUT, resp.getStatusLine().getStatusCode());
    System.out.println(resp.getStatusLine().getStatusCode());
}

我的课程只是在万一发生故障时用断路器运行web get/puts/etc。我的班级如下:
public class CircuitBreaker extends HystrixCommand<HttpResponse> {
 private HttpClient client;
 private HttpRequestBase req;
 protected String key;
//Set up logger
 private static final Logger logger = (Logger)LoggerFactory.getLogger(CircuitBreaker.class);

  /*
  * This method is a constructor and sets http client based on provides args.
  * This version accepts user input Hystrix key.
  */
  public CircuitBreaker (HttpClient client, String key, HttpRequestBase req, int threshold) {
      super(HystrixCommandGroupKey.Factory.asKey(key));
      this.client = client;
      this.key = key;
      this.req = req;
      logger.info("Hystrix Circut Breaker with Hystrix key:" + key);
      logger.setLevel(Level.DEBUG);
      HystrixCommandProperties.Setter().withCircuitBreakerEnabled(true);
      HystrixCommandProperties.Setter().withCircuitBreakerErrorThresholdPercentage(threshold);
      //HystrixCommandProperties.Setter().withCircuitBreakerRequestVolumeThreshold(50);
  }
  /*
   * This method is a constructor and sets http client based on provides args.
   * This version uses the default threshold of 50% failures if one isn't provided.
   */
  public CircuitBreaker (HttpClient client,String key, HttpRequestBase req){
      this(client, key, req, 50);
  }
  /*
  * This method runs the command and returns the response.
  */
@Override
protected HttpResponse run() throws Exception {
    HttpResponse resp = null;
    resp = client.execute(req);
    if (resp != null)
        logger.info("Request to " + req.getURI() + " succeeded!");
    return resp;
}
/*
 * Fallback method in in the event the circuit breaker is tripped.
 * Overriding the default fallback implemented by Hystrix that just throws an exception.
 * @see com.netflix.hystrix.HystrixCommand#getFallback()
 */
@Override
protected HttpResponse getFallback() {
    //For later expansion as needed.
    logger.error("Circuit Breaker has " + getExecutionEvents() + ". Reason: "+ getFailedExecutionException().getMessage());
    return null;
}
}

最佳答案

您可以尝试增加断路器的超时时间,看看会发生什么:

HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(5000)

因为根据Hystrix Wiki,hystrixcommand的默认超时为1秒,httpget返回某些内容可能需要1秒以上的时间。

关于java - 增加Hystrix断路器超时?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36631389/

10-11 04:16