分布式配置中心 Apollo 实战 - Apollo 客户端使用手册
Java 客户端使用指南
环境准备
JDK8+
Guava 20.0+
(Apollo
客户端默认会引入Guava 29
)
必选配置
Apollo
客户端依赖于 AppId
、Apollo Meta Server
等环境信息来读取配置。
AppId
普通应用(非 Spring Boot
应用):推荐使用 VM Options
进行配置:
1 | -Dapp.id=YOUR-APP-ID |
Spring Boot
应用:推荐在 application.properties
配置文件中配置:
1 | app.id=YOUR-APP-ID |
Apollo Meta Server
Apollo
支持同一个 AppId
(应用)在不同环境下有不同的配置,所以需要提供给 Apollo
客户端在当前环境下运行的 Apollo Meta Server
地址。默认情况下,Meta Server
和 Config Service
部署在同一个 JVM
进程中,所以 Meta Server
地址就是 Config Service
的地址。
普通应用(非 Spring Boot
应用):推荐使用 VM Options
配置:
1 | -Dapollo.meta=http://config-service-url |
Spring Boot
应用:
推荐一:使用
VM Options
配置:首先配置环境
env
,如果当前env
是DEV
,则配置dev_meta
:1
-Denv=DEV -Ddev_meta=http://config-service-url
推荐二:使用
apollo-env.properties
文件:
在 Spring Boot
应用的 resources
目录下(classpath
下)创建 apollo-env.properties
文件,配置形式如下:
1 | dev.meta=http://apollo-dev.xxx.com |
然后配置环境 env
,如果当前是 DEV
环境,则在 VM Options
中指定 -Denv=DEV
。
跳过 Apollo Meta Server 服务发现
实际企业开发中,Config Service
很可能部署在 Docker
环境下,注册到 Meta Server
的是内网地址,本地开发环境无法直连 Meta Server
。针对这种场景,我们可以跳过 Meta Server
的服务发现,直接指定 Config Service
的地址进行直连。
推荐使用 VM Options
配置:
1 | -Dapollo.config-service=http://config-service-url |
可选配置
Environment 环境
推荐使用 VM Options
配置:
1 | -Denv=DEV |
env
取值(大小写不敏感)可参考 Apollo
源码的 com.ctrip.framework.apollo.core.enums.Env.java
枚举类。
Cluster 集群
推荐使用 VM Options
配置:
1 | -Dapollo.cluster=hangzhou-cluster |
maven 坐标
1 | <!-- apollo客户端 --> |
API 使用
以 user-service
为例,首先需要在控制台初始化一些配置以供读取。
创建标准 maven
工程 apollo-samples
,编写 main
方法,添加 VM Options
参数配置:
1 | -Dapp.id=user-service -Denv=DEV -Ddev_meta=http://localhost:8080 |
下面是相关 API
使用示例:
读取默认 namespace(application)下的配置项
1 | private static void readDefaultNamespaceConfig() { |
读取指定 namespace 下的配置项
1 | private static void readSpecifyNamespaceConfig() { |
读取公共 namespace 下的配置项
1 | private static void readCommonNamespaceConfig() { |
读取 yaml/yml 格式的 namespace 下的配置项
1 | private static void readYamlFormatNamespaceConfig() { |
读取非 yaml/yml 格式的 namespace 配置内容
1 | private static void readNotYamlFormatNamespace() { |
监听配置项变更事件
1 | private static void listenConfigChangeEvent() { |