1 pom.xml加入依赖
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-client</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-core</artifactId>
<version>1.1.0</version>
2 添加app.properties文件到META-INF下
3 在springboot启动类上方加入@EnableApolloConfig注解
4 登陆apollo配置中心创建项目,增加配置
这里定义了三个环境分别是:
DEV:开发环境
TEST:测试环境
DEMO:演示环境
(生产环境是PROD,在另一个apollo配置中心)
5 根据不同环境加载配置
pom.xml中加入profile配置
<profiles>
<profile>
<id>develop</id>
<properties>
<profiles.active>env-dev</profiles.active>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>test</id>
<properties>
<profiles.active>env-test</profiles.active>
</properties>
</profile>
<profile>
<id>product</id>
<properties>
<profiles.active>env-prod</profiles.active>
</properties>
</profile>
<profile>
<id>demo</id>
<properties>
<profiles.active>env-demo</profiles.active>
</properties>
</profile>
</profiles>
我把4个profile配置文件放在了environment下
里面的配置就一个key:env,env的值对应apollo配置中心里项目的环境
然后创建application.properties,增加avtive.env=${env}
下面我们就需要修改springboot启动类,直接上代码
public static void main(String[] args) throws Exception {
//读取application.properties获取编译后的active.env值
Properties properties = new Properties();
InputStream in = SnowApplication.class.getClassLoader().getResourceAsStream("application.properties");
properties.load(in);
String env = properties.getProperty("active.env");
//设置apollo启动环境
System.setProperty("env", env);
//设置apollo meta server
if("PROD".equals(env)){
System.setProperty("apollo.meta","http://test.xx.apollo.com");
}else{
System.setProperty("apollo.meta","http://xx.apollo.com");
}
SpringApplication.run(SnowApplication.class, args);
log.info("SpringBoot Start Success, running environment is {}", env);
}
因为在pom中定义了默认启用profile为develop,对应的env-dev.properties里面的env为DEV,即开发环境,直接启动时会去加载apollo中对应的DEV环境配置,所以开发时可以直接使用。在其他环境下,因为我们使用了jenkins自动构建,只需根据不同环境在maven打包命令上加入 -Ptest 、-Pdemo、-Pproduct 即可。
到此为止,表达能力有限,不明白的可以留言哦。