拥有 Feign 客户端:
@FeignClient(name = "storeClient", url = "${feign.url}")
public interface StoreClient {
//..
}
是否可以利用 Spring Cloud 的环境更改功能在运行时更改 Feign url?(更改feign.url
属性并调用/refresh
端点)
拥有 Feign 客户端:
@FeignClient(name = "storeClient", url = "${feign.url}")
public interface StoreClient {
//..
}
是否可以利用 Spring Cloud 的环境更改功能在运行时更改 Feign url?(更改feign.url
属性并调用/refresh
端点)
作为一种可能的解决方案 -RequestInterceptor
可以引入以便RequestTemplate
从RefreshScope
.
要实施这种方法,您应该执行以下操作:
ConfigurationProperties
Component
中定义RefreshScope
@Component
@RefreshScope
@ConfigurationProperties("storeclient")
public class StoreClientProperties {
private String url;
...
}
指定客户端的默认 URLapplication.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());
}
}
在 URL的定义中使用一些占位符FeignClient
,因为它不会被使用
@FeignClient(name = "storeClient", url = "NOT_USED")
public interface StoreClient {
//..
}
现在storeclient.url
可以刷新,定义的 URL 将用于RequestTemplate
发送 http 请求。
有点扩展的答案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 {
...
}