在运行时更改FeignClient网址

Grz*_*ski 5 spring-cloud spring-cloud-feign

有假装客户介绍:

@FeignClient(name = "storeClient", url = "${feign.url}")
public interface StoreClient {
    //..
}
Run Code Online (Sandbox Code Playgroud)

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

Ale*_*hin 3

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

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

  1. 定义ConfigurationProperties ComponentRefreshScope

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

    storeclient
        url: https://someurl
    
    Run Code Online (Sandbox Code Playgroud)
  3. 定义RequestInterceptor将切换 URL

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

    @FeignClient(name = "storeClient", url = "NOT_USED")
    public interface StoreClient {
        //..
    }
    
    Run Code Online (Sandbox Code Playgroud)

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