0

我的@Service 类中有一个用@HystrixCommand 标记的函数。

此方法充当客户端,向另一个服务 URL 发送请求并返回响应。

我想要做的是在响应状态代码不是 200 时触发回退功能。它还将触发任何其他异常(RuntimeExceptions 等)的回退。

我想通过使用@HystrixProperty 或@HystrixCommandProperty 来做到这一点。

我希望客户端 ping URL 并监听 200 响应状态,如果它在某个时间范围内没有返回 200 状态,我希望它回退。

如果它在一定时间内正常返回 200 状态,则不应触发回退。

@HystrixCommand(fallbackMethod="fallbackPerformOperation")
    public Future<Object> performOperation(String requestString) throws InterruptedException 

        return new AsyncResult<Object>() {

            @Override
            public Object invoke() {

                Client client = null;
                WebResource webResource  = null;
                ClientResponse response =null;
                String results = null; 
                try{
                    client = Client.create();       
                    webResource = client.resource(URL);
                    client.setConnectTimeout(10000);
                    client.setReadTimeout(10000);
                    response = webResource.type("application/xml")
                       .post(ClientResponse.class, requestString);  

              } finally {
                  client.destroy();
                  webResource = null;
              }

                return results;
            }

        };
}

我特别想使用@HystrixProperty@HystrixCommandProperty,因此在方法内部执行检查以确保响应状态代码不是200,然后抛出异常是不可接受的。

通过扩展 HystrixCommand 接口工作而不是使用注释来创建我自己的命令?

任何我可以从这里开始的想法或资源都非常受欢迎。

4

1 回答 1

0

我不明白你为什么不想检查响应http状态码,如果不是200就抛出异常?这样做会给你你想要的行为。即它将触发异常或非 200 响应的回退。

您可以在客户端设置超时,但我会选择使用 hystrix 超时值。这样,如果需要,您可以使用Archaius在运行时动态更改值。

您可以使用 Hystrix 命令注释或扩展 HystrixCommand 类。这两个选项都将为您提供所需的行为

这是使用注释的示例。

 @HystrixCommand(fallbackMethod = "getRequestFallback")
  public String performGetRequest(String uri) {
    Client client = Client.create();
    WebResource webResource = client.resource(uri);
    ClientResponse response = webResource.get(ClientResponse.class);
    if (response.getStatus() != 200) {
      throw new RuntimeException("Invalid response status");
    }
    return response.getEntity(String.class);
  }

  public String getRequestFallback(String uri) {
    return "Fallback Value";
  }
于 2018-01-19T09:34:45.197 回答