how to change the @FeignClient name in runtime

时间:2016-02-03 03:48:47

标签: spring spring-cloud

I use Spring Cloud Netflix to build my micro service .

@FeignClient(name = "ms-cloud",configuration = MsCloudClientConfig.class)      
public interface TestClient {                                                  

/**                                                                        
 * @return                                                                 
 */                                                                        
@RequestMapping(value = "/test", method = RequestMethod.GET)               
String test();                                                             

}  

I want to change the name to ms-cloud-pre when some special user. Anyone can give some advice?

3 个答案:

答案 0 :(得分:1)

根据documentation假设支持nameurl字段中的占位符。

@FeignClient(name = "${store.name}")
public interface StoreClient {
    //..
}

因此,您可以使用普通的Spring启动配置机制在运行时设置store.name=storeProd

答案 1 :(得分:0)

实际上这是可能的。在Spring Cloud Zookeeper中,我们做了类似的事情,因为Feign客户端中的服务名称不是Zookeeper中的服务名称。它可以是yaml文件中显示的别名。这里有代码示例https://github.com/spring-cloud/spring-cloud-zookeeper/blob/master/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/discovery/dependency/DependencyRibbonAutoConfiguration.java#L54,您可以在此处获得依赖项功能的说明 - https://github.com/spring-cloud/spring-cloud-zookeeper/blob/master/docs/src/main/asciidoc/spring-cloud-zookeeper.adoc#using-the-zookeeper-dependencies

答案 2 :(得分:0)

要在直到调用点才知道服务ID的情况下在运行时创建spring-cloud Feign客户端:

import org.springframework.cloud.openfeign.FeignClientBuilder;

@Component
public class InfoFeignClient {

  interface InfoCallSpec {
    @RequestMapping(value = "/actuator/info", method = GET)
    String info();
  }

  FeignClientBuilder feignClientBuilder;

  public InfoFeignClient(@Autowired ApplicationContext appContext) {
    this.feignClientBuilder = new FeignClientBuilder(appContext);
  }

  public String getInfo(String serviceId) {

    InfoCallSpec spec =
        this.feignClientBuilder.forType(InfoCallSpec.class, serviceId).build();

    return spec.info();
  }
}