FeignClient自调用问题处理

项目中使用feignClient时,有时会遇到自调用情况,即A服务通过feignClient,调用了自己服务的接口。这种情况一般是由于错误的方法使用,不正确的feignClient依赖导致,应予以修正。

但也有一些情况,比如依赖的外部sdk包中的service方法里,通过feignClient调用了远程方法,而这个远程方法的服务方正是自己(比如serviceA)。在这种情况下,可以通过以下步骤进行处理,将远程调用变为本地方法直接执行:

  1. 在定义远程调用的FeignClient类上,声明primary值为true:

    @FeignClient(value = "serviceA", contextId = "testFeign", path = "busitest", primary = false)
    public interface TestFeign {
     @GetMapping
     public String get();
    }
  2. 将对应实现该FeignClient方法的Controller类上,补全继承关系,并声明@Primary:

    @RequestMapping("busitest")
    @RestController
    @Primary
    public class BusiTestController implements TestFeign{
     
     @GetMapping
     public String get(){
         return "get";
     }
    }

    完成以上步骤后,重新部署api包。此时如果某服务的sdk包中存在如下Service:

    @Service
    public class BusiService{
      @Autowired
      private TestFeign testFeign;
     
     
      public Strinmg busiMethod(){
     testFeign.get();
      }
    }

    则该Service在serviceA之外的服务中使用时,执行busiMethod方法,会通过feignClient向serviceA发起远程调用;而在serviceA服务本身使用这个Service时,执行busiMethod方法,会直接执行BusiTestController的get()方法,而不再通过feignClient去处理请求。

你可能感兴趣的:(FeignClient自调用问题处理)