Изменить URL-адрес FeignClient во время выполнения

Наличие клиента Feign в представленном виде:

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

Можно ли использовать возможности Spring Cloud для изменения среды для изменения URL-адреса Feign во время выполнения? (Изменение свойства feign.url и вызов конечной точки /refresh)


person Grzegorz Poznachowski    schedule 22.09.2017    source источник


Ответы (2)


В качестве возможного решения можно ввести RequestInterceptor, чтобы установить URL-адрес в RequestTemplate из свойства, определенного в файле RefreshScope.

Для реализации этого подхода необходимо сделать следующее:

  1. Определите ConfigurationProperties Component в RefreshScope

    @Component
    @RefreshScope
    @ConfigurationProperties("storeclient")
    public class StoreClientProperties {
        private String url;
        ...
    }
    
  2. Укажите URL по умолчанию для клиента в application.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. Используйте какой-нибудь заполнитель в вашем определении FeignClient для URL, потому что он не будет использоваться.

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

Теперь storeclient.url можно обновить, и указанный URL будет использоваться в RequestTemplate для отправки HTTP-запроса.

person Aleksandr Erokhin    schedule 04.09.2018

Немного расширенный ответ с 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-с конфигурация

Убедитесь, что ваш класс ...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 {
    ...
}
person fightlight    schedule 15.10.2020