如何根据属性文件更改外部客户端url



我有一个Feign客户端,它向给定的url 发送请求

@FeignClient(
name = "feign-client-name",
url = "${feign.client.url}",
configuration = FeignClientConfiguration.class)
public interface SomeFeignClient {
@GetMapping(SOME_GEP_MAPPING_PATH)
Entity getEntity(String id);
}
feign:
client:
url: https://url-to-service.com
token: secret_token
internal-url: https://url-to-internal-service.com
internal: on

@RequiredArgsConstructor
public class FeignClientConfiguration {
private final FeignProperties properties;
@Bean
public RequestInterceptor requestInterceptor() {
return template -> {
template.header(HttpHeaders.AUTHORIZATION, "Token " + properties.getToken());
template.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
template.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
};
}
}

如何根据internal属性更改外部客户端的url
我希望它以以下方式工作:如果internal属性的值为on,则在其他情况下,外部客户端应使用internal-url值和url

UPD:
可能的解决方案-使用Spring Profiles。

我找到了没有Spring配置文件的解决方案
这个灵魂的主要思想是使用@ConditionalOnProperty注释,防止bean的创建依赖于特定的属性。在这种情况下,

首先,我们需要创建新的接口,例如SomeFeignClient

public interface SomeFeignClient {
Entity getEntity(String id);
}

其次,创建2个Feign客户端,它们将扩展我们的接口,并使用@ConditionalOnProperty注释进行标记

@ConditionalOnProperty(prefix="feign.client", name="internal", havingValue="true")
@FeignClient(...your configurations here...)
public interface SomeFeignClientFirst extends SomeFeignClient {
@Override
Entity getEntity(String id);
}
@ConditionalOnProperty(prefix="feign.client", name="internal", havingValue="false")
@FeignClient(...your configurations here...)
public interface SomeFeignClientSecond extends SomeFeignClient {
@Override
Entity getEntity(String id);
}

如果你想为这个外国客户端添加请求拦截器,不要忘记使用@ConditionalOnBean注释标记它们

@RequiredArgsConstructor
public class FeignClientConfiguration {
private final FeignProperties properties;

@ConditionalOnBean(SomeFeignClientFirst.class)
@Bean
public RequestInterceptor requestInterceptor() {
return template -> {
template.header(HttpHeaders.AUTHORIZATION, "Token " + properties.getToken());
template.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
template.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
};
}
  1. 对于所有类型的环境相关属性,请使用Spring概要文件。与DEV-env类似,您将具有特定于DEV的属性,类似于prod-env、test-env等。更多信息:使用Spring Profiles

  2. 当您使用Feign客户端,并且您有Eureka服务器时,请尝试通过Eureka进行服务发现。只为您要查找的Feign客户端传递服务名称。如果您的微服务在尤里卡注册,它将从那里找到,不需要硬编码的URL。Spring Cloud集成了Ribbon和Eureka,在使用Feign时提供负载平衡的http客户端。更多信息:Spring Cloud OpenFeign

最新更新