@AuthorizedFeignClient 中的动态主机名

Dynamic hostname in @AuthorizedFeignClient

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

我尝试在应用程序中添加-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: Invalid bean definition with name 'com.sistema.service.util.EmailClient' defined in null: Could not resolve placeholder 'containers-host.gateway' in value "http://${containers-host.gateway}:8080/utils/api/email"; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'containers-host.gateway' in value "http://${containers-host.gateway}:8080/utils/api/email" 2018-11-08 11:25:22.101 ERROR 64 --- [ main] o.s.boot.SpringApplication : Application run failed

org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'com.sistema.service.util.EmailClient' defined in null: Could not resolve placeholder 'containers-host.gateway' in value "http://${containers-host.gateway}:8080/utils/api/email"; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'containers-host.gateway' in value "http://${containers-host.gateway}:8080/utils/api/email"

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

我失败的代码如下所示:

@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 注释创建配置 class。

.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")