Mr.*_*Eng 6 java spring configuration-files spring-boot microservices
我正在尝试使用 spring 和 spring boot 开发微服务。在我的项目中,我正在将整体架构转换为面向服务的架构。项目包含 20 个微服务。我需要设置应用程序变量和全局变量。我有与此相关的困惑,我在这里添加这些困惑,
经过我的探索,我找到了加载全局变量和应用程序变量(包括数据库配置)问题的解决方案。我们可以使用的最好方法是 - Spring Cloud 配置服务器外部化配置。
我们可以为 Spring Cloud 配置服务器创建一个微服务。在配置服务器中,我们可以通过两种方式创建变量和配置。
链接参考
这里我遵循使用本地文件系统。
需要在 src/main/resources 下创建 Config 文件夹。并按照命名约定创建不同的配置文件,
db,properties 、 db-test.properties 、 db-prod.properties 、 db-dev.properties 。我为不同的开发环境创建了例如。就像我们可以为变量和配置创建任何配置文件一样。
并在配置服务器的 application.properties 中添加以下内容
server.port=8888
spring.profiles.active=native
Run Code Online (Sandbox Code Playgroud)
在配置服务器的pom.xml文件中添加配置服务器依赖,
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)
将以下内容添加到主应用程序运行类中,
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
Run Code Online (Sandbox Code Playgroud)
并通过添加 pom.xml 依赖项来创建客户端微服务项目,
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)
在 application.properties 文件中添加以下行以设置客户端从服务器接收配置,
server.port=8080
spring.application.name=db
spring.cloud.config.uri=localhost:8888
Run Code Online (Sandbox Code Playgroud)
最后通过指定 profile 运行您的客户端项目,
java -jar -Dsping.profiles.active=<profile> <jar_name>.jar
Run Code Online (Sandbox Code Playgroud)
提前致谢
归档时间: |
|
查看次数: |
24920 次 |
最近记录: |