7

拥有 Feign 客户端:

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

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

4

2 回答 2

3

作为一种可能的解决方案 -RequestInterceptor可以引入以便RequestTemplateRefreshScope.

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

  1. ConfigurationProperties Component中定义RefreshScope

    @Component
    @RefreshScope
    @ConfigurationProperties("storeclient")
    public class StoreClientProperties {
        private String url;
        ...
    }
    
  2. 指定客户端的默认 URLapplication.yml

    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. 在 URL的定义中使用一些占位符FeignClient,因为它不会被使用

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

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

于 2018-09-04T11:23:23.463 回答
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 {
    ...
}
于 2020-10-15T11:12:09.333 回答