在运行时更改FeignClient URL

时间:2017-09-22 13:33:40

标签: spring-cloud spring-cloud-feign

将Feign客户端呈现为:

@FeignClient(name = "storeClient", url = "${feign.url}")
public interface StoreClient {
    //..
}

是否可以利用环境变化的Spring Cloud功能在运行时更改Feign URL? (更改feign.url属性并调用/refresh端点)

2 个答案:

答案 0 :(得分:0)

作为一种可能的解决方案-可以引入RequestInterceptor以便通过RequestTemplate中定义的属性在RefreshScope中设置URL。

要实施此方法,您应该执行以下操作:

  1. ConfigurationProperties

    中定义Component RefreshScope
    @Component
    @RefreshScope
    @ConfigurationProperties("storeclient")
    public class StoreClientProperties {
        private String url;
        ...
    }
    
  2. application.yml

    中指定客户端的默认URL
    storeclient
        url: https://someurl
    
  3. 定义RequestInterceptor,它将切换URL

    @Configuration
    public class StoreClientConfiguration {
    
        @Autowired
        private StoreClientProperties storeClientProperties;
    
        @Bean
        public RequestInterceptor urlInterceptor() {
            return template -> template.insert(0, storeClientProperties.getUrl());
        }
    
    }
    
  4. 在您的FeignClient定义中使用一些占位符作为URL,因为它将不被使用

    @FeignClient(name = "storeClient", url = "NOT_USED")
    public interface StoreClient {
        //..
    }
    

现在storeclient.url可以刷新,定义的URL将在RequestTemplate中用于发送http请求。

答案 1 :(得分:0)

RequestInterceptor的扩展答案:

  1. application.yml
app:
  api-url: http://external.system/messages
  callback-url: http://localhost:8085/callback
  1. @ConfigurationProperties
@Component
@RefreshScope
@ConfigurationProperties("app")
public class AppProperties {
    private String apiUrl;
    private String callbackUrl;
    ...
}
  1. @FeignClient-s配置

请确保您的...ClientConfig类未使用任何@Component / ...注释进行注释,或者未通过组件扫描找到。

public class ApiClientConfig {
    @Bean
    public RequestInterceptor requestInterceptor(AppProperties appProperties) {
        return requestTemplate -> requestTemplate.target(appProperties.getApiUrl());
    }
}
public class CallbackClientConfig {
    @Bean
    public RequestInterceptor requestInterceptor(AppProperties appProperties) {
        return requestTemplate -> requestTemplate.target(appProperties.getCallbackUrl());
    }
}
  1. @FeignClient-s
@FeignClient(name = "apiClient", url = "NOT_USED", configuration = ApiClientConfig.class)
public interface ApiClient {
    ...
}
@FeignClient(name = "callbackClient", url = "NOT_USED", configuration = CallbackClientConfig.class)
public interface CallbackClient {
    ...
}