具有假装客户端:
@FeignClient(name = "storeClient", url = "${feign.url}")
public interface StoreClient {
//..
}
是否可以利用环境更改的 Spring Cloud 功能在运行时更改 Feign url?(更改feign.url
属性并调用/refresh
终结点)
作为一种可能的解决方案 - 可以引入RequestInterceptor
以便从RefreshScope
中定义的属性RequestTemplate
中设置 URL。
要实现此方法,应执行以下操作:
-
在
RefreshScope
中定义ConfigurationProperties
Component
@Component @RefreshScope @ConfigurationProperties("storeclient") public class StoreClientProperties { private String url; ... }
-
在
application.yml
中指定客户端的默认 URLstoreclient url: https://someurl
-
定义将切换 URL 的
RequestInterceptor
@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 {
...
}