@AuthorizedFeignClient中的动态主机名



在微服务系统中,我有一个带有注释@AuthorizedFeignClient(name="send-email", url="http://localhost:8080/utils/api/email")的接口,在开发环境中它可以正常工作,但在Docker环境中,我需要url参数来使用Docker容器名称来代替localhost,以便在Docker环境中工作。

我尝试在application-prod.yml中添加配置:

containers-host:
gateway: jhipster-gateway

在注释中,我是这样写的:

@AuthorizedFeignClient(name="send-email", url="http://${containers-host.gateway}:8080/utils/api/email")

然而,当试图生成.war时,它失败了:

org.springframework.beans.factory.BeanDefinitionStoreException:在null中定义的名称为"com.sistema.service.util.EmailClient"的bean定义无效:无法解析值"http://${containers host.gateway}:8080/utils/api/email"中的占位符"containers host.gateway";嵌套异常为java.lang.IollegalArgumentException:无法解析值"http://${containers host.gateway}:8080/utils/api/email"中的占位符"containers host.gateway"2018-11-08 11:25:22.101错误64---[main]o.s.boot.SpringApplication:应用程序运行失败

org.springframework.beans.factory.BeanDefinitionStoreException:在null中定义的名称为"com.sistema.service.util.EmailClient"的bean定义无效:无法解析值"http://${containers host.gateway}:8080/utils/api/email"中的占位符"containers host.gateway";嵌套异常为java.lang.IollegalArgumentException:无法解析值"http://${containers host.gateway}:8080/utils/api/email"中的占位符"containers host.gateway">

如何根据服务运行的环境配置设置服务的主机名?

我失败的代码如下:

@AuthorizedFeignClient(name="send-email", url="http://${containers-host.gateway}:8080/utils/api/email")
public interface EmailClient {
@PostMapping("/send-email")
void sendEmail(String mail);
}

要设置在application-dev.yml或application-prod.yml中输入的值,需要创建一个带有@ConfigurationProperties注释的配置类。

在.yml文件中:

microservices:
gateway: http://environment-host:8080

以这种方式创建配置文件:

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "microservices", ignoreUnknownFields = false)
public class MicroservicesConectionProperties {
private String gateway = "";
public String getGateway() {
return gateway;
}
public void setGateway(String gateway) {
this.gateway = gateway;
} 
}

并使@AuthorizedFeignClient像这样:

@AuthorizedFeignClient(name="send-email", url="${microservices.gateway}/utils/api/email")

最新更新