【问题标题】:Global variables And Application Variables Defining in Spring boot projectSpring Boot项目中定义的全局变量和应用程序变量
【发布时间】:2018-09-04 12:56:24
【问题描述】:

我正在尝试使用 spring 和 spring boot 来开发微服务。在我的项目中,我正在将单体架构转换为面向服务的架构。项目包含20个微服务。我需要设置应用程序变量和全局变量。我有与此相关的困惑,我在这里添加这些困惑,

  1. 是否可以在 application.properties 文件中声明我的全局变量?如果不可能,我可以在哪里定义我的全局变量?
  2. 如果我使用 spring 配置服务器进行全局配置,如何有条件地将这些属性导入客户端项目?
  3. 我可以在配置服务器中为不同的配置文件设置不同的属性文件,并有条件地为不同的配置文件导入客户端项目吗?在我的例子中,每个配置文件代表不同的区域。

【问题讨论】:

  • 您可以使用基于键值的存储,例如 etcd 来存储全局变量
  • 或一个公共的休息服务,它将返回你的全局变量。
  • 或者你可以有一个父工件来存储你的全局变量
  • 需要良好的架构设置研发 :-)
  • 耶。我得到了一种可行的方法 Mr.Kakabali。无论如何,感谢您的回复和与我共度时光。你可以用我的方法来交叉检查你的发现。我已经添加了缺点。

标签: java spring spring-boot microservices configuration-files


【解决方案1】:

经过我的探索,我找到了加载全局变量和应用程序变量(包括数据库配置)的解决方案。我们可以使用的最佳方式是 - spring cloud config server externalized configuration。

我们可以为spring cloud config server创建一个微服务。在配置服务器中,我们可以通过两种方式创建变量和配置。

  1. 来自 GIT 链接参考的配置
  2. 使用本地文件系统/环境变量。

参考链接

  1. https://cloud.spring.io/spring-cloud-config/single/spring-cloud-config.html
  2. https://cloud.spring.io/spring-cloud-static/spring-cloud-config/1.3.3.RELEASE/multi/multi__spring_cloud_config_server.html
  3. https://github.com/spring-cloud/spring-cloud-config

这里我使用本地文件系统。

需要在 src/main/resources 下创建 Config 文件夹。并按照命名约定创建不同的配置文件,

db、properties、db-test.properties、db-prod.properties、db-dev.properties。 例如,我为不同的开发环境创建了示例。就像我们可以为变量和配置创建任何配置文件一样。

并在配置服务器的 application.properties 中添加以下内容

server.port=8888
spring.profiles.active=native

在配置服务器的pom.xml文件中添加配置服务器依赖,

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-server</artifactId>
</dependency>

将以下内容添加到主应用程序运行类中,

@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {

    public static void main(String[] args) {
    SpringApplication.run(ConfigServerApplication.class, args);
    }
}

并且还通过添加pom.xml依赖创建客户端微服务项目,

<dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-config</artifactId>
</dependency>

在 application.properties 文件中添加以下行用于设置客户端从服务器接收配置,

server.port=8080
spring.application.name=db
spring.cloud.config.uri=localhost:8888

最后通过指定 profile 来运行你的客户项目,

java -jar -Dsping.profiles.active=<profile> <jar_name>.jar

提前致谢

【讨论】:

  • 非常感谢您的研究!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-30
  • 2015-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多