【问题标题】:Can I dynamic create a Feign Client or create an instance with a different name我可以动态创建一个 Feign 客户端或创建一个不同名称的实例吗
【发布时间】:2023-03-25 07:22:01
【问题描述】:

我定义了一个 REST 接口,它使用不同的 spring.application.namespring.application.name 在我的业务中不能相同)具有不同的 Spring Boot 应用程序实现。

如何只定义一个Feign Client,并且可以访问所有的SpringBootApplication REST Services?

SpringBootApplication A(spring.application.name=A) 和 B(spring.application.name=) 有这个 RestService:

@RestController
@RequestMapping(value = "/${spring.application.name}")
public class FeignRestService {

    @Autowired
    Environment env;

    @RequestMapping(path = "/feign")
    public String feign() {
        return env.getProperty("server.port");
    }
}

另一个 SpringBootApplication C:

@FeignClient(name="SpringApplication A or B")
public interface FeignClientService {

    @RequestMapping(path = "/feign")
    public String feign();
}

在SpringBootApplication C中,我想使用一个FeignClientService来访问A和B,你有什么想法吗?

【问题讨论】:

    标签: spring-boot spring-cloud-netflix spring-cloud-feign netflix-ribbon feign


    【解决方案1】:

    您可能已经想通了,但这可能会帮助任何正在寻找相同问题答案的人。您需要为使用服务的每个服务客户端配置 Feign 客户端。

    无法使用同一个 Feign 客户端调用不同的服务,因为 Feign 客户端与您定义的服务绑定。

    【讨论】:

      【解决方案2】:

      是的,您可以创建一个 Feign 客户端,并根据需要重复使用它来调用 Eureka 目录中的不同命名服务(您使用 spring-cloud-netflix 标记了问题)。以下是您如何执行此操作的示例:

      @Component
      public class DynamicFeignClient {
      
        interface MyCall {
          @RequestMapping(value = "/rest-service", method = GET)
          void callService();
        }
      
        FeignClientBuilder feignClientBuilder;
      
        public DynamicFeignClient(@Autowired ApplicationContext appContext) {
          this.feignClientBuilder = new FeignClientBuilder(appContext);
        }
      
        /*
         * Dynamically call a service registered in the directory.
         */
      
        public void doCall(String serviceId) {
      
          // create a feign client
      
          MyCall fc =
              this.feignClientBuilder.forType(MyCall.class, serviceId).build();
      
          // make the call
      
          fc.callService();
        }
      }
      

      调整调用接口以满足您的要求,然后您可以将DynamicFeignClient 实例注入并使用到您需要使用它的bean。

      几个月来,我们一直在生产中使用这种方法来询问数十种不同的服务,以获取版本信息和其他有用的运行时执行器数据等内容。

      【讨论】:

      • 你好,这个 feignClientBuilder 怎么做测试?
      猜你喜欢
      • 1970-01-01
      • 2018-07-10
      • 2012-11-28
      • 1970-01-01
      • 2011-04-25
      • 2020-09-12
      • 2014-03-20
      • 2015-07-02
      • 2012-01-26
      相关资源
      最近更新 更多