关于feign:Spring-CloudFeign调用异常触发降级后如何捕获异常

47次阅读

共计 1130 个字符,预计需要花费 3 分钟才能阅读完成。

一、问题背景

在 Spring Cloud 的微服务架构中,通常微服务之间通过 feign/openfeign 来进行 http 调用,并且 启用 hystrix 并配置降级策略 fallback,能够在 http 调用异样时触发降级,代码如下

@FeignClient(name = "resourceFeign", fallback = ResourceFeignFallback.class)
public interface ResourceFeign {@PostMapping("/resource/list")
    Map<String, Object> resourceList();}

@Component
public class ResourceFeignFallback implements ResourceFeign {

  @Override
  public Map<String, Object> resourceList() {Map result = new HashMap<>();
    result.put("code", 500);
    result.put("msg", "申请异样");
    return result;
  }
}

然而这种形式在 http 调用异样时,会间接执行降级策略,而 无奈捕捉到具体的异样信息,这种状况如何解决?

二、解决办法

所以咱们通常应用另一种形式,通过配置 fallbackFactory 来捕捉异样信息,代码如下

@FeignClient(name = "resourceFeign", fallbackFactory = ResourceFeignFallbackFactory.class)
public interface ResourceFeign {@PostMapping("/resource/list")
    Map<String, Object> resourceList();}

@Component
@Slf4j
public class ResourceWebFeignFallbackFactory implements FallbackFactory<ResourceFeign> {

    @Override
    public ResourceFeign create(Throwable throwable) {
        // 捕捉异样
        log.error(throwable.getMessage());

        return new ResourceFeign() {
            @Override
            public Map<String, Object> resourceList() {Map result = new HashMap<>();
                  result.put("code", 500);
                  result.put("msg", "申请异样");
                  return result;
            }
        };
    }
}

这样就能够捕捉到 http 调用的异样信息

正文完
 0