【问题标题】:How to log the reason that hystrix fallback method invoked如何记录调用 hystrix 回退方法的原因
【发布时间】:2018-11-14 17:40:16
【问题描述】:

我正在使用 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);
    }
}

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

如何记录触发回退方法调用的异常?
比如connectionTimeoutException。

【问题讨论】:

    标签: spring-cloud hystrix netflix-feign feign


    【解决方案1】:

    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);
        }
    
    }
    

    你的后备类看起来像

    @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
       }
    
    }
    

    您还需要更改一些配置类

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

    【讨论】:

    • 我编辑了这个问题。 fallback 类实现了 FeignClient 的接口。如何获取 throwable 参数?
    猜你喜欢
    • 2017-05-03
    • 2020-11-22
    • 2023-02-22
    • 2020-01-25
    • 2017-06-18
    • 2017-10-10
    • 2019-11-05
    • 2020-08-08
    • 2013-12-26
    相关资源
    最近更新 更多