【问题标题】:how to change the @FeignClient name in runtime如何在运行时更改@FeignClient 名称
【发布时间】:2016-02-03 03:48:47
【问题描述】:

我使用 Spring Cloud Netflix 构建我的微服务。

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

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

}  

我想在某些特殊用户时将名称更改为 ms-cloud-pre。 谁能给点建议?

【问题讨论】:

    标签: spring spring-cloud


    【解决方案1】:

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

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

    因此您可以在运行时使用正常的 Spring Boot 配置机制设置 store.name=storeProd

    【讨论】:

    • 注意:您不能根据参数或本地上下文动态更改它。
    • 作为普通用户,store.name=storeProd,但有一些凭证,store.name=storeProd-pre,。
    • 不,你不能那样做。
    【解决方案2】:

    在调用点之前不知道 service-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();
      }
    }
    

    【讨论】:

      【解决方案3】:

      这实际上是可能的。在 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

      【讨论】:

      • 也许这是一种优雅的实现方式
      • 是疑问句还是陈述句? :P 我的意思是它对你有帮助吗?
      • 现在我使用eureka作为注册服务器中心
      • 因此您可以使用与我向您展示的方法相同的方法。没有开箱即用的东西。您必须自己构建它。
      猜你喜欢
      • 2018-03-04
      • 1970-01-01
      • 2016-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-16
      • 2018-07-09
      • 1970-01-01
      相关资源
      最近更新 更多