springboot 集成apollo,根据不同环境加载配置

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 即可。

到此为止,表达能力有限,不明白的可以留言哦。

  • 2
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值