Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change FeignClient url at runtime

Having Feign client as presented:

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

Is is possible to make use of Spring Cloud capabilities of environment changes to change the Feign url at runtime? (Changing the feign.url property and invoking /refresh endpoint)

like image 993
Grzegorz Poznachowski Avatar asked Sep 22 '17 13:09

Grzegorz Poznachowski


1 Answers

As a possible solution - RequestInterceptor could be introduced in order to set URL in RequestTemplate from a property defined in the RefreshScope.

To implement this approach you should do the following:

  1. Define ConfigurationProperties Component in the RefreshScope

    @Component
    @RefreshScope
    @ConfigurationProperties("storeclient")
    public class StoreClientProperties {
        private String url;
        ...
    }
    
  2. Specify default URL for the client in the application.yml

    storeclient
        url: https://someurl
    
  3. Define RequestInterceptor that will switch URL

    @Configuration
    public class StoreClientConfiguration {
    
        @Autowired
        private StoreClientProperties storeClientProperties;
    
        @Bean
        public RequestInterceptor urlInterceptor() {
            return template -> template.insert(0, storeClientProperties.getUrl());
        }
    
    }
    
  4. Use some placeholder in your FeignClient definition for the URL, because it will not be used

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

Now storeclient.url can be refreshed and the URL defined will be used in RequestTemplate to sent http request.

like image 118
Aleksandr Erokhin Avatar answered Sep 24 '22 08:09

Aleksandr Erokhin