如何记录 hystrix 回退方法调用的原因

How to log the reason that hystrix fallback method invoked

我正在使用 Fiegn 创建一个 REST 客户端。我的调用正常,但我想记录触发回退方法调用的异常。
代码如下:

public interface FooService {
    Foo queryFoo(Integer fooId);
}

public interface FooServiceFallback implements FooService {
    @Override
    Foo queryFoo(Integer fooId) {
        return new Foo();
    }
}

@Configuration
public class FooServiceConfiguration {
    @Bean
    public FooService() {
        return HystrixFeign.builder().[...].target(FooService.class, "http://xxx", FooServiceFallback.class);
    }
}

发生异常时可以调用回退方法,但会记录注释。

如何记录触发回退方法调用的异常?
像连接超时异常。

Fallback 方法可以采用类型为 Throwable 的额外参数,这将指示原因。

例如如果你的方法是这样的

@HystrixCommand(fallbackMethod = "fallbackMethod")
public String mainMethod(String s) {
 .....
}

你的后备方法可以是这样的

public String fallbackMethod(String s) {
     ......
}

public String fallbackMethod(String s, Throwable throwable) {
     //log the cause using throwable instance
     ......
}

在你的情况下使用第二个。

编辑:

如果您正在使用 HystrixFeign,这就是您的做法。你应该使用 FallbackFactory

@Component
public class FooServiceFallbackFactory implements FallbackFactory<FooService> {

    @Override
    public FooService create(Throwable throwable) {
        return new FooServiceFallback(throwable);
    }

}

你的备用 class 看起来像

@Component
public class FooServiceFallback implements FooService {

   private final Throwable cause;

   public FooServiceFallback(Throwable cause) {
      this.cause = cause;
   }

   @Override
   Foo queryFoo(Integer fooId) {
       //You have access to cause now, which will have the real exception thrown
   }

}

您还需要更改一些配置 class

@Configuration
public class FooServiceConfiguration {
    @Bean
    public FooService() {
        return HystrixFeign.builder().[...].target(FooService.class, "http://xxx", FooServiceFallbackFactory.class);
    }
}