Spring Cloud全解析:服务调用之多个FeignClient调用服务名称相同


文章目录


name相同问题

在使用@FeignClient的时候,发现多个@FeignClient中的name相同就无法启动,当然了,这是因为bean名称重复了,创建bean的时候报的错,但是如何解决呢?

A bean with that name has already been defined and overriding is disabled

可以配置不同的contextId来进行解决

@FeignClient(name = "SPRINGCLOUD2-PROVIDER",contextId = "DeptClient",fallbackFactory = DeptClientFallBackFactory.class)
public interface DeptClient {

    @GetMapping(value = "/dept/get/{id}")
    CommonResult<Dept> get(@PathVariable("id") long id);

    @GetMapping("/timeout")
    String timeout();
}


@FeignClient(name = "SPRINGCLOUD2-PROVIDER",contextId = "DeptClient1",fallbackFactory = DeptClientFallBackFactory.class)
public interface DeptClient1 {

    @GetMapping(value = "/dept/get/{id}")
    CommonResult<Dept> get(@PathVariable("id") long id);

    @GetMapping("/timeout")
    String timeout();
}

为什么可以这样解决呢?

String name = getClientName(attributes);
registerClientConfiguration(registry, name,
      attributes.get("configuration"));

在FeignClientsRegistrar中进行@FeignClient注册时,对于bean的名称是调用getClientName(Map<String, Object> client)方法来获取的

private String getClientName(Map<String, Object> client) {
   if (client == null) {
      return null;
   }
   String value = (String) client.get("contextId");
   if (!StringUtils.hasText(value)) {
      value = (String) client.get("value");
   }
   if (!StringUtils.hasText(value)) {
      value = (String) client.get("name");
   }
   if (!StringUtils.hasText(value)) {
      value = (String) client.get("serviceId");
   }
   if (StringUtils.hasText(value)) {
      return value;
   }

   throw new IllegalStateException("Either 'name' or 'value' must be provided in @"
         + FeignClient.class.getSimpleName());
}

代码也比较简单,可以看到是先获取的contextId,如果配置了 contextId 就会用 contextId,如果没有配置就会取 value 然后是 name 最后是 serviceId

获取到clientName之后进行bean注册

private void registerClientConfiguration(BeanDefinitionRegistry registry, Object name,
      Object configuration) {
   BeanDefinitionBuilder builder = BeanDefinitionBuilder
         .genericBeanDefinition(FeignClientSpecification.class);
   builder.addConstructorArgValue(name);
   builder.addConstructorArgValue(configuration);
   registry.registerBeanDefinition(
         name + "." + FeignClientSpecification.class.getSimpleName(),
         builder.getBeanDefinition());
}

拼接的beanName就是clientName.FeignClientSpecification

参考文献

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

拾光师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值