将Feign客户端呈现为:
@FeignClient(name = "storeClient", url = "${feign.url}")
public interface StoreClient {
//..
}
是否可以利用环境变化的Spring Cloud功能在运行时更改Feign URL? (更改feign.url
属性并调用/refresh
端点)
答案 0 :(得分:0)
作为一种可能的解决方案-可以引入RequestInterceptor
以便通过RequestTemplate
中定义的属性在RefreshScope
中设置URL。
要实施此方法,您应该执行以下操作:
在ConfigurationProperties
Component
RefreshScope
@Component
@RefreshScope
@ConfigurationProperties("storeclient")
public class StoreClientProperties {
private String url;
...
}
在application.yml
storeclient
url: https://someurl
定义RequestInterceptor
,它将切换URL
@Configuration
public class StoreClientConfiguration {
@Autowired
private StoreClientProperties storeClientProperties;
@Bean
public RequestInterceptor urlInterceptor() {
return template -> template.insert(0, storeClientProperties.getUrl());
}
}
在您的FeignClient
定义中使用一些占位符作为URL,因为它将不被使用
@FeignClient(name = "storeClient", url = "NOT_USED")
public interface StoreClient {
//..
}
现在storeclient.url
可以刷新,定义的URL将在RequestTemplate
中用于发送http请求。
答案 1 :(得分:0)
RequestInterceptor
的扩展答案:
application.yml
app:
api-url: http://external.system/messages
callback-url: http://localhost:8085/callback
@ConfigurationProperties
@Component
@RefreshScope
@ConfigurationProperties("app")
public class AppProperties {
private String apiUrl;
private String callbackUrl;
...
}
@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());
}
}
@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 {
...
}