添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

1.2 必选设置

Apollo客户端依赖于 AppId Apollo Meta Server 等环境信息来工作,所以请确保阅读下面的说明并且做正确的配置:

1.2.1 AppId

AppId是应用的身份信息,是从服务端获取配置的一个重要信息。

有以下几种方式设置,按照优先级从高到低分别为:

  • System Property
  • Apollo 0.7.0+支持通过System Property传入app.id信息,如

    -Dapp.id=YOUR-APP-ID
  • 操作系统的System Environment
  • Apollo 1.4.0+支持通过操作系统的System Environment APP_ID 来传入app.id信息,如

    APP_ID=YOUR-APP-ID
  • Spring Boot application.properties
  • Apollo 1.0.0+支持通过Spring Boot的application.properties文件配置,如

    app.id=YOUR-APP-ID

    该配置方式不适用于多个war包部署在同一个tomcat的使用场景

  • app.properties
  • 确保classpath:/META-INF/app.properties文件存在,并且其中内容形如:

    app.id=YOUR-APP-ID

    文件位置参考如下:

    注:app.id是用来标识应用身份的唯一id,格式为string。

    1.2.2 Apollo Meta Server

    Apollo支持应用在不同的环境有不同的配置,所以需要在运行提供给Apollo客户端当前环境的 Apollo Meta Server 信息。默认情况下,meta server和config service是部署在同一个JVM进程,所以meta server的地址就是config service的地址。

    为了实现meta server的高可用,推荐通过SLB(Software Load Balancer)做动态负载均衡。Meta server地址也可以填入IP,如 http://1.1.1.1:8080,http://2.2.2.2:8080 ,不过生产环境还是建议使用域名(走slb),因为机器扩容、缩容等都可能导致IP列表的变化。

    1.0.0版本开始支持以下方式配置apollo meta server信息,按照优先级从高到低分别为:

  • 通过Java System Property apollo.meta
  • 可以通过Java的System Property apollo.meta 来指定
  • 在Java程序启动脚本中,可以指定 -Dapollo.meta=http://config-service-url
  • 如果是运行jar文件,需要注意格式是 java -Dapollo.meta=http://config-service-url -jar xxx.jar
  • 也可以通过程序指定,如 System.setProperty("apollo.meta", "http://config-service-url");
  • 通过Spring Boot的配置文件
  • 可以在Spring Boot的 application.properties bootstrap.properties 中指定 apollo.meta=http://config-service-url
  • 通过 server.properties 配置文件
  • 可以在 server.properties 配置文件中指定 apollo.meta=http://config-service-url
  • 对于Mac/Linux,文件位置为 /opt/settings/server.properties
  • 对于Windows,文件位置为 C:\opt\settings\server.properties
  • 通过 app.properties 配置文件
  • 可以在 classpath:/META-INF/app.properties 指定 apollo.meta=http://config-service-url
  • 通过Java system property ${env}_meta
  • 如果当前 env dev ,那么用户可以配置 -Ddev_meta=http://config-service-url
  • 使用该配置方式,那么就必须要正确配置Environment,详见 1.2.4.1 Environment
  • 通过操作系统的System Environment ${ENV}_META (1.2.0版本开始支持)
  • 如果当前 env dev ,那么用户可以配置操作系统的System Environment DEV_META=http://config-service-url
  • 注意key为全大写
  • 使用该配置方式,那么就必须要正确配置Environment,详见 1.2.4.1 Environment
  • 通过 apollo-env.properties 文件
  • 用户也可以创建一个 apollo-env.properties ,放在程序的classpath下,或者放在spring boot应用的config目录下
  • 使用该配置方式,那么就必须要正确配置Environment,详见 1.2.4.1 Environment
  • 文件内容形如:
  • dev.meta=http://1.1.1.1:8080
    fat.meta=http://apollo.fat.xxx.com
    uat.meta=http://apollo.uat.xxx.com
    pro.meta=http://apollo.xxx.com

    如果通过以上各种手段都无法获取到Meta Server地址,Apollo最终会fallback到 http://apollo.meta 作为Meta Server地址

    1.2.2.1 自定义Apollo Meta Server地址定位逻辑

    在1.0.0版本中,Apollo提供了 MetaServerProvider SPI ,用户可以注入自己的MetaServerProvider来自定义Meta Server地址定位逻辑。

    由于我们使用典型的 Java Service Loader模式 ,所以实现起来还是比较简单的。

    有一点需要注意的是,apollo会在运行时按照顺序遍历所有的MetaServerProvider,直到某一个MetaServerProvider提供了一个非空的Meta Server地址,因此用户需要格外注意自定义MetaServerProvider的Order。规则是较小的Order具有较高的优先级,因此Order=0的MetaServerProvider会排在Order=1的MetaServerProvider的前面。

    如果你的公司有很多应用需要接入Apollo,建议封装一个jar包,然后提供自定义的Apollo Meta Server定位逻辑,从而可以让接入Apollo的应用零配置使用。比如自己写一个 xx-company-apollo-client ,该jar包依赖 apollo-client ,在该jar包中通过spi方式定义自定义的MetaServerProvider实现,然后应用直接依赖 xx-company-apollo-client 即可。

    MetaServerProvider的实现可以参考 LegacyMetaServerProvider DefaultMetaServerProvider

    1.2.2.2 跳过Apollo Meta Server服务发现

    适用于apollo-client 0.11.0及以上版本

    一般情况下都建议使用Apollo的Meta Server机制来实现Config Service的服务发现,从而可以实现Config Service的高可用。不过apollo-client也支持跳过Meta Server服务发现,主要用于以下场景:

  • Config Service部署在公有云上,注册到Meta Server的是内网地址,本地开发环境无法直接连接
  • Config Service部署在docker环境中,注册到Meta Server的是docker内网地址,本地开发环境无法直接连接
  • Config Service部署在kubernetes中,希望使用kubernetes自带的服务发现能力(Service)
  • 针对以上场景,可以通过直接指定Config Service地址的方式来跳过Meta Server服务发现,按照优先级从高到低分别为:

  • 通过Java System Property apollo.configService
  • 可以通过Java的System Property apollo.configService 来指定
  • 在Java程序启动脚本中,可以指定 -Dapollo.configService=http://config-service-url:port
  • 如果是运行jar文件,需要注意格式是 java -Dapollo.configService=http://config-service-url:port -jar xxx.jar
  • 也可以通过程序指定,如 System.setProperty("apollo.configService", "http://config-service-url:port");
  • 通过操作系统的System Environment APOLLO_CONFIGSERVICE
  • 可以通过操作系统的System Environment APOLLO_CONFIGSERVICE 来指定
  • 注意key为全大写,且中间是 _ 分隔
  • 通过 server.properties 配置文件
  • 可以在 server.properties 配置文件中指定 apollo.configService=http://config-service-url:port
  • 对于Mac/Linux,文件位置为 /opt/settings/server.properties
  • 对于Windows,文件位置为 C:\opt\settings\server.properties
  • 1.2.3 本地缓存路径

    Apollo客户端会把从服务端获取到的配置在本地文件系统缓存一份,用于在遇到服务不可用,或网络不通的时候,依然能从本地恢复配置,不影响应用正常运行。

    本地缓存路径默认位于以下路径,所以请确保 /opt/data C:\opt\data\ 目录存在,且应用有读写权限。

  • Mac/Linux: /opt/data/{ appId }/config-cache
  • Windows: C:\opt\data\{ appId }\config-cache
  • 本地配置文件会以下面的文件名格式放置于本地缓存路径下:

    {appId}+{cluster}+{namespace}.properties

  • appId就是应用自己的appId,如100004458
  • cluster就是应用使用的集群,一般在本地模式下没有做过配置的话,就是default
  • namespace就是应用使用的配置namespace,一般是application client-local-cache
  • 文件内容以properties格式存储,比如如果有两个key,一个是request.timeout,另一个是batch,那么文件内容就是如下格式:

    request.timeout=2000
    batch=2000

    1.2.3.1 自定义缓存路径

    1.0.0版本开始支持以下方式自定义缓存路径,按照优先级从高到低分别为:

  • 通过Java System Property apollo.cacheDir
  • 可以通过Java的System Property apollo.cacheDir 来指定
  • 在Java程序启动脚本中,可以指定 -Dapollo.cacheDir=/opt/data/some-cache-dir
  • 如果是运行jar文件,需要注意格式是 java -Dapollo.cacheDir=/opt/data/some-cache-dir -jar xxx.jar
  • 也可以通过程序指定,如 System.setProperty("apollo.cacheDir", "/opt/data/some-cache-dir");
  • 通过Spring Boot的配置文件
  • 可以在Spring Boot的 application.properties bootstrap.properties 中指定 apollo.cacheDir=/opt/data/some-cache-dir
  • 通过操作系统的System Environment APOLLO_CACHEDIR
  • 可以通过操作系统的System Environment APOLLO_CACHEDIR 来指定
  • 注意key为全大写,且中间是 _ 分隔
  • 通过 server.properties 配置文件
  • 可以在 server.properties 配置文件中指定 apollo.cacheDir=/opt/data/some-cache-dir
  • 对于Mac/Linux,文件位置为 /opt/settings/server.properties
  • 对于Windows,文件位置为 C:\opt\settings\server.properties
  • 注:本地缓存路径也可用于容灾目录,如果应用在所有config service都挂掉的情况下需要扩容,那么也可以先把配置从已有机器上的缓存路径复制到新机器上的相同缓存路径

    1.2.4 可选设置

    1.2.4.1 Environment

    Environment可以通过以下3种方式的任意一个配置:

    通过Java System Property

  • 可以通过Java的System Property env 来指定环境
  • 在Java程序启动脚本中,可以指定 -Denv=YOUR-ENVIRONMENT
  • 如果是运行jar文件,需要注意格式是 java -Denv=YOUR-ENVIRONMENT -jar xxx.jar
  • 注意key为全小写
  • 通过操作系统的System Environment

  • 还可以通过操作系统的System Environment ENV 来指定
  • 注意key为全大写
  • 通过配置文件

  • 最后一个推荐的方式是通过配置文件来指定 env=YOUR-ENVIRONMENT
  • 对于Mac/Linux,文件位置为 /opt/settings/server.properties
  • 对于Windows,文件位置为 C:\opt\settings\server.properties
  • 文件内容形如:

    env=DEV

    目前, env 支持以下几个值(大小写不敏感):

  • Development environment
  • Feature Acceptance Test environment
  • User Acceptance Test environment
  • Production environment
  • 更多环境定义,可以参考 Env.java

    1.2.4.2 Cluster(集群)

    Apollo支持配置按照集群划分,也就是说对于一个appId和一个环境,对不同的集群可以有不同的配置。

    1.0.0版本开始支持以下方式集群,按照优先级从高到低分别为:

  • 通过Java System Property apollo.cluster
  • 可以通过Java的System Property apollo.cluster 来指定
  • 在Java程序启动脚本中,可以指定 -Dapollo.cluster=SomeCluster
  • 如果是运行jar文件,需要注意格式是 java -Dapollo.cluster=SomeCluster -jar xxx.jar
  • 也可以通过程序指定,如 System.setProperty("apollo.cluster", "SomeCluster");
  • 通过Spring Boot的配置文件
  • 可以在Spring Boot的 application.properties bootstrap.properties 中指定 apollo.cluster=SomeCluster
  • 通过Java System Property
  • 可以通过Java的System Property idc 来指定环境
  • 在Java程序启动脚本中,可以指定 -Didc=xxx
  • 如果是运行jar文件,需要注意格式是 java -Didc=xxx -jar xxx.jar
  • 注意key为全小写
  • 通过操作系统的System Environment
  • 还可以通过操作系统的System Environment IDC 来指定
  • 注意key为全大写
  • 通过 server.properties 配置文件
  • 可以在 server.properties 配置文件中指定 idc=xxx
  • 对于Mac/Linux,文件位置为 /opt/settings/server.properties
  • 对于Windows,文件位置为 C:\opt\settings\server.properties
  • Cluster Precedence(集群顺序)

    如果 apollo.cluster idc 同时指定:

  • 我们会首先尝试从 apollo.cluster 指定的集群加载配置
  • 如果没找到任何配置,会尝试从 idc 指定的集群加载配置
  • 如果还是没找到,会从默认的集群( default )加载
  • 如果只指定了 apollo.cluster

  • 我们会首先尝试从 apollo.cluster 指定的集群加载配置
  • 如果没找到,会从默认的集群( default )加载
  • 如果只指定了 idc

  • 我们会首先尝试从 idc 指定的集群加载配置
  • 如果没找到,会从默认的集群( default )加载
  • 如果 apollo.cluster idc 都没有指定:

  • 我们会从默认的集群( default )加载配置
  • 1.2.4.3 设置内存中的配置项是否保持和页面上的顺序一致

    适用于1.6.0及以上版本

    默认情况下,apollo client内存中的配置存放在Properties中(底下是Hashtable),不会刻意保持和页面上看到的顺序一致,对绝大部分的场景是没有影响的。不过有些场景会强依赖配置项的顺序(如spring cloud zuul的路由规则),针对这种情况,可以开启OrderedProperties特性来使得内存中的配置顺序和页面上看到的一致。

    配置方式按照优先级从高到低分别为:

  • 通过Java System Property apollo.property.order.enable
  • 可以通过Java的System Property apollo.property.order.enable 来指定
  • 在Java程序启动脚本中,可以指定 -Dapollo.property.order.enable=true
  • 如果是运行jar文件,需要注意格式是 java -Dapollo.property.order.enable=true -jar xxx.jar
  • 也可以通过程序指定,如 System.setProperty("apollo.property.order.enable", "true");
  • 通过Spring Boot的配置文件
  • 可以在Spring Boot的 application.properties bootstrap.properties 中指定 apollo.property.order.enable=true
  • 通过 app.properties 配置文件
  • 可以在 classpath:/META-INF/app.properties 指定 apollo.property.order.enable=true
  • 二、Maven Dependency

    Apollo的客户端jar包已经上传到中央仓库,应用在实际使用时只需要按照如下方式引入即可。

        <dependency>
            <groupId>com.ctrip.framework.apollo</groupId>
            <artifactId>apollo-client</artifactId>
            <version>1.1.0</version>
        </dependency>

    三、客户端用法

    Apollo支持API方式和Spring整合方式,该怎么选择用哪一种方式?

  • API方式灵活,功能完备,配置值实时更新(热发布),支持所有Java环境。
  • Spring方式接入简单,结合Spring有N种酷炫的玩法,如
  • Placeholder方式:
  • 代码中直接使用,如: @Value("${someKeyFromApollo:someDefaultValue}")
  • 配置文件中使用替换placeholder,如: spring.datasource.url: ${someKeyFromApollo:someDefaultValue}
  • 直接托管spring的配置,如在apollo中直接配置 spring.datasource.url=jdbc:mysql://localhost:3306/somedb?characterEncoding=utf8
  • Spring boot的 @ConfigurationProperties 方式
  • 从v0.10.0开始的版本支持placeholder在运行时自动更新,具体参见 PR #972 。(v0.10.0之前的版本在配置变化后不会重新注入,需要重启才会更新,如果需要配置值实时更新,可以参考后续 3.2.2 Spring Placeholder的使用 的说明)
  • Spring方式也可以结合API方式使用,如注入Apollo的Config对象,就可以照常通过API方式获取配置了:
    @ApolloConfig
    private Config config; //inject config for namespace application
  • 更多有意思的实际使用场景和示例代码,请参考 apollo-use-cases
  • 3.1 API使用方式

    API方式是最简单、高效使用Apollo配置的方式,不依赖Spring框架即可使用。

    3.1.1 获取默认namespace的配置(application)

    Config config = ConfigService.getAppConfig(); //config instance is singleton for each namespace and is never null
    String someKey = "someKeyFromDefaultNamespace";
    String someDefaultValue = "someDefaultValueForTheKey";
    String value = config.getProperty(someKey, someDefaultValue);

    通过上述的config.getProperty可以获取到someKey对应的实时最新的配置值。

    另外,配置值从内存中获取,所以不需要应用自己做缓存。

    3.1.2 监听配置变化事件

    监听配置变化事件只在应用真的关心配置变化,需要在配置变化时得到通知时使用,比如:数据库连接串变化后需要重建连接等。

    如果只是希望每次都取到最新的配置的话,只需要按照上面的例子,调用config.getProperty即可。

    Config config = ConfigService.getAppConfig(); //config instance is singleton for each namespace and is never null
    config.addChangeListener(new ConfigChangeListener() {
        @Override
        public void onChange(ConfigChangeEvent changeEvent) {
            System.out.println("Changes for namespace " + changeEvent.getNamespace());
            for (String key : changeEvent.changedKeys()) {
                ConfigChange change = changeEvent.getChange(key);
                System.out.println(String.format("Found change - key: %s, oldValue: %s, newValue: %s, changeType: %s", change.getPropertyName(), change.getOldValue(), change.getNewValue(), change.getChangeType()));
    
    
    String somePublicNamespace = "CAT";
    Config config = ConfigService.getConfig(somePublicNamespace); //config instance is singleton for each namespace and is never null
    String someKey = "someKeyFromPublicNamespace";
    String someDefaultValue = "someDefaultValueForTheKey";
    String value = config.getProperty(someKey, someDefaultValue);

    3.1.4 获取非properties格式namespace的配置

    3.1.4.1 yaml/yml格式的namespace

    apollo-client 1.3.0版本开始对yaml/yml做了更好的支持,使用起来和properties格式一致。

    Config config = ConfigService.getConfig("application.yml");
    String someKey = "someKeyFromYmlNamespace";
    String someDefaultValue = "someDefaultValueForTheKey";
    String value = config.getProperty(someKey, someDefaultValue);

    3.1.4.2 非yaml/yml格式的namespace

    获取时需要使用ConfigService.getConfigFile接口并指定Format,如ConfigFileFormat.XML

    String someNamespace = "test";
    ConfigFile configFile = ConfigService.getConfigFile("test", ConfigFileFormat.XML);
    String content = configFile.getContent();

    3.2 Spring整合方式

    3.2.1 配置

    Apollo也支持和Spring整合(Spring 3.1.1+),只需要做一些简单的配置就可以了。

    Apollo目前既支持比较传统的基于XML的配置,也支持目前比较流行的基于Java(推荐)的配置。

    如果是Spring Boot环境,建议参照3.2.1.3 Spring Boot集成方式(推荐)配置。

    需要注意的是,如果之前有使用org.springframework.beans.factory.config.PropertyPlaceholderConfigurer的,请替换成org.springframework.context.support.PropertySourcesPlaceholderConfigurer。Spring 3.1以后就不建议使用PropertyPlaceholderConfigurer了,要改用PropertySourcesPlaceholderConfigurer。

    如果之前有使用<context:property-placeholder>,请注意xml中引入的spring-context.xsd版本需要是3.1以上(一般只要没有指定版本会自动升级的),建议使用不带版本号的形式引入,如:http://www.springframework.org/schema/context/spring-context.xsd

    注1:yaml/yml格式的namespace从1.3.0版本开始支持和Spring整合,注入时需要填写带后缀的完整名字,比如application.yml

    注2:非properties、非yaml/yml格式(如xml,json等)的namespace暂不支持和Spring整合。

    3.2.1.1 基于XML的配置

    注:需要把apollo相关的xml namespace加到配置文件头上,不然会报xml语法错误。

    1.注入默认namespace的配置到Spring中

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:apollo="http://www.ctrip.com/schema/apollo"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.ctrip.com/schema/apollo http://www.ctrip.com/schema/apollo.xsd">
        <!-- 这个是最简单的配置形式,一般应用用这种形式就可以了,用来指示Apollo注入application namespace的配置到Spring环境中 -->
        <apollo:config/>
        <bean class="com.ctrip.framework.apollo.spring.TestXmlBean">
            <property name="timeout" value="${timeout:100}"/>
            <property name="batch" value="${batch:200}"/>
        </bean>
    </beans>

    2.注入多个namespace的配置到Spring中

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:apollo="http://www.ctrip.com/schema/apollo"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.ctrip.com/schema/apollo http://www.ctrip.com/schema/apollo.xsd">
        <!-- 这个是最简单的配置形式,一般应用用这种形式就可以了,用来指示Apollo注入application namespace的配置到Spring环境中 -->
        <apollo:config/>
        <!-- 这个是稍微复杂一些的配置形式,指示Apollo注入FX.apollo和application.yml namespace的配置到Spring环境中 -->
        <apollo:config namespaces="FX.apollo,application.yml"/>
        <bean class="com.ctrip.framework.apollo.spring.TestXmlBean">
            <property name="timeout" value="${timeout:100}"/>
            <property name="batch" value="${batch:200}"/>
        </bean>
    </beans>

    3.注入多个namespace,并且指定顺序

    Spring的配置是有顺序的,如果多个property source都有同一个key,那么最终是顺序在前的配置生效。

    apollo:config如果不指定order,那么默认是最低优先级。

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:apollo="http://www.ctrip.com/schema/apollo"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.ctrip.com/schema/apollo http://www.ctrip.com/schema/apollo.xsd">
        <apollo:config order="2"/>
        <!-- 这个是最复杂的配置形式,指示Apollo注入FX.apollo和application.yml namespace的配置到Spring环境中,并且顺序在application前面 -->
        <apollo:config namespaces="FX.apollo,application.yml" order="1"/>
        <bean class="com.ctrip.framework.apollo.spring.TestXmlBean">
            <property name="timeout" value="${timeout:100}"/>
            <property name="batch" value="${batch:200}"/>
        </bean>
    </beans>

    3.2.1.2 基于Java的配置(推荐)

    相对于基于XML的配置,基于Java的配置是目前比较流行的方式。

    注意@EnableApolloConfig要和@Configuration一起使用,不然不会生效。

    1.注入默认namespace的配置到Spring中

    //这个是最简单的配置形式,一般应用用这种形式就可以了,用来指示Apollo注入application namespace的配置到Spring环境中
    @Configuration
    @EnableApolloConfig
    public class AppConfig {
      @Bean
      public TestJavaConfigBean javaConfigBean() {
        return new TestJavaConfigBean();
    

    2.注入多个namespace的配置到Spring中

    @Configuration
    @EnableApolloConfig
    public class SomeAppConfig {
      @Bean
      public TestJavaConfigBean javaConfigBean() {
        return new TestJavaConfigBean();
    //这个是稍微复杂一些的配置形式,指示Apollo注入FX.apollo和application.yml namespace的配置到Spring环境中
    @Configuration
    @EnableApolloConfig({"FX.apollo", "application.yml"})
    public class AnotherAppConfig {}

    3.注入多个namespace,并且指定顺序

    //这个是最复杂的配置形式,指示Apollo注入FX.apollo和application.yml namespace的配置到Spring环境中,并且顺序在application前面
    @Configuration
    @EnableApolloConfig(order = 2)
    public class SomeAppConfig {
      @Bean
      public TestJavaConfigBean javaConfigBean() {
        return new TestJavaConfigBean();
    @Configuration
    @EnableApolloConfig(value = {"FX.apollo", "application.yml"}, order = 1)
    public class AnotherAppConfig {}

    Spring Boot除了支持上述两种集成方式以外,还支持通过application.properties/bootstrap.properties来配置,该方式能使配置在更早的阶段注入,比如使用@ConditionalOnProperty的场景或者是有一些spring-boot-starter在启动阶段就需要读取配置做一些事情(如dubbo-spring-boot-project),所以对于Spring Boot环境建议通过以下方式来接入Apollo(需要0.10.0及以上版本)。

    使用方式很简单,只需要在application.properties/bootstrap.properties中按照如下样例配置即可。

  • 注入默认application namespace的配置示例
  •      # will inject 'application' namespace in bootstrap phase
         apollo.bootstrap.enabled = true
  • 注入非默认application namespace或多个namespace的配置示例
  •      apollo.bootstrap.enabled = true
         # will inject 'application', 'FX.apollo' and 'application.yml' namespaces in bootstrap phase
         apollo.bootstrap.namespaces = application,FX.apollo,application.yml
  • 将Apollo配置加载提到初始化日志系统之前(1.2.0+)
  • 从1.2.0版本开始,如果希望把日志相关的配置(如logging.level.root=infologback-spring.xml中的参数)也放在Apollo管理,那么可以额外配置apollo.bootstrap.eagerLoad.enabled=true来使Apollo的加载顺序放到日志系统加载之前,不过这会导致Apollo的启动过程无法通过日志的方式输出(因为执行Apollo加载的时候,日志系统压根没有准备好呢!所以在Apollo代码中使用Slf4j的日志输出便没有任何内容),更多信息可以参考PR 1614。参考配置示例如下:

         # will inject 'application' namespace in bootstrap phase
         apollo.bootstrap.enabled = true
         # put apollo initialization before logging system initialization
         apollo.bootstrap.eagerLoad.enabled=true

    3.2.2 Spring Placeholder的使用

    Spring应用通常会使用Placeholder来注入配置,使用的格式形如${someKey:someDefaultValue},如${timeout:100}。冒号前面的是key,冒号后面的是默认值。

    建议在实际使用时尽量给出默认值,以免由于key没有定义导致运行时错误。

    从v0.10.0开始的版本支持placeholder在运行时自动更新,具体参见PR #972

    如果需要关闭placeholder在运行时自动更新功能,可以通过以下两种方式关闭:

    通过设置System Property apollo.autoUpdateInjectedSpringProperties,如启动时传入-Dapollo.autoUpdateInjectedSpringProperties=false

    通过设置META-INF/app.properties中的apollo.autoUpdateInjectedSpringProperties属性,如

    app.id=SampleApp
    apollo.autoUpdateInjectedSpringProperties=false

    3.2.2.1 XML使用方式

    假设我有一个TestXmlBean,它有两个配置项需要注入:

    public class TestXmlBean {
      private int timeout;
      private int batch;
      public void setTimeout(int timeout) {
        this.timeout = timeout;
      public void setBatch(int batch) {
        this.batch = batch;
      public int getTimeout() {
        return timeout;
      public int getBatch() {
        return batch;
    

    那么,我在XML中会使用如下方式来定义(假设应用默认的application namespace中有timeout和batch的配置项):

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:apollo="http://www.ctrip.com/schema/apollo"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.ctrip.com/schema/apollo http://www.ctrip.com/schema/apollo.xsd">
        <apollo:config/>
        <bean class="com.ctrip.framework.apollo.spring.TestXmlBean">
            <property name="timeout" value="${timeout:100}"/>
            <property name="batch" value="${batch:200}"/>
        </bean>
    </beans>

    假设我有一个TestJavaConfigBean,通过Java Config的方式还可以使用@Value的方式注入:

    public class TestJavaConfigBean {
      @Value("${timeout:100}")
      private int timeout;
      private int batch;
      @Value("${batch:200}")
      public void setBatch(int batch) {
        this.batch = batch;
      public int getTimeout() {
        return timeout;
      public int getBatch() {
        return batch;
    

    在Configuration类中按照下面的方式使用(假设应用默认的application namespace中有timeoutbatch的配置项):

    @Configuration
    @EnableApolloConfig
    public class AppConfig {
      @Bean
      public TestJavaConfigBean javaConfigBean() {
        return new TestJavaConfigBean();
    
    

    Spring Boot提供了@ConfigurationProperties把配置注入到bean对象中。

    Apollo也支持这种方式,下面的例子会把redis.cache.expireSecondsredis.cache.commandTimeout分别注入到SampleRedisConfig的expireSecondscommandTimeout字段中。

    @ConfigurationProperties(prefix = "redis.cache")
    public class SampleRedisConfig {
      private int expireSeconds;
      private int commandTimeout;
      public void setExpireSeconds(int expireSeconds) {
        this.expireSeconds = expireSeconds;
      public void setCommandTimeout(int commandTimeout) {
        this.commandTimeout = commandTimeout;
    

    在Configuration类中按照下面的方式使用(假设应用默认的application namespace中有redis.cache.expireSecondsredis.cache.commandTimeout的配置项):

    @Configuration
    @EnableApolloConfig
    public class AppConfig {
      @Bean
      public SampleRedisConfig sampleRedisConfig() {
        return new SampleRedisConfig();
    

    需要注意的是,@ConfigurationProperties如果需要在Apollo配置变化时自动更新注入的值,需要配合使用EnvironmentChangeEventRefreshScope。相关代码实现,可以参考apollo-use-cases项目中的ZuulPropertiesRefresher.java和apollo-demo项目中的SampleRedisConfig.java以及SpringBootApolloRefreshConfig.java

    3.2.3 Spring Annotation支持

    Apollo同时还增加了几个新的Annotation来简化在Spring环境中的使用。

  • @ApolloConfig
  • 用来自动注入Config对象
  • @ApolloConfigChangeListener
  • 用来自动注册ConfigChangeListener
  • @ApolloJsonValue
  • 用来把配置的json字符串自动注入为对象
  • 使用样例如下:

    public class TestApolloAnnotationBean {
      @ApolloConfig
      private Config config; //inject config for namespace application
      @ApolloConfig("application")
      private Config anotherConfig; //inject config for namespace application
      @ApolloConfig("FX.apollo")
      private Config yetAnotherConfig; //inject config for namespace FX.apollo
      @ApolloConfig("application.yml")
      private Config ymlConfig; //inject config for namespace application.yml
       * ApolloJsonValue annotated on fields example, the default value is specified as empty list - []
       * <br />
       * jsonBeanProperty=[{"someString":"hello","someInt":100},{"someString":"world!","someInt":200}]
      @ApolloJsonValue("${jsonBeanProperty:[]}")
      private List<JsonBean> anotherJsonBeans;
      @Value("${batch:100}")
      private int batch;
      //config change listener for namespace application
      @ApolloConfigChangeListener
      private void someOnChange(ConfigChangeEvent changeEvent) {
        //update injected value of batch if it is changed in Apollo
        if (changeEvent.isChanged("batch")) {
          batch = config.getIntProperty("batch", 100);
      //config change listener for namespace application
      @ApolloConfigChangeListener("application")
      private void anotherOnChange(ConfigChangeEvent changeEvent) {
        //do something
      //config change listener for namespaces application, FX.apollo and application.yml
      @ApolloConfigChangeListener({"application", "FX.apollo", "application.yml"})
      private void yetAnotherOnChange(ConfigChangeEvent changeEvent) {
        //do something
      //example of getting config from Apollo directly
      //this will always return the latest value of timeout
      public int getTimeout() {
        return config.getIntProperty("timeout",