在运行时更改FeignClient URL

问题描述 投票:4回答:1

有Feign客户端呈现:

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

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

spring-cloud spring-cloud-feign
1个回答
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. 定义将切换URL的RequestInterceptor @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请求。

© www.soinside.com 2019 - 2024. All rights reserved.