apollo客户端是解决应用如何从apollo配置中心获取参数
一、主要概念
1、appid:用来标识应用身份的唯一id
确保classpath:/META-INF/app.properties文件存在,并且其中内容形如:
app.id=YOUR-APP-ID
2、Apollo Meta Server:当前环境信息(区分各个环境)
通过app.properties配置文件
可以在classpath:/META-INF/app.properties指定apollo.meta=http://config-service-url
3、namespace:namespace是配置项的集合,类似于一个配置文件的概念
默认namespace是application,对应配置文件application.properties
4、namespace分类
私有类型:私有的只有本项目可以使用
公有类型:公有的namespace所有的项目都可以读
私有和公有关系:如果公有的namespace和私有的namespace中有相同的key,私用的会覆盖公有中的值
5、创建一个yml格式的application
可以看到多了一个namespace
点击发布(只有发布过的配置才会被客户端获取到,此次发布只会作用于当前环境:DEV)
PS:修改了下值,加了引号,yml会把没有引号的0当做数字
二、引入jar包
mycloud-service-provider1和mycloud-service-provider2模块,引入:
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-client</artifactId>
<version>1.6.0</version>
</dependency>
三、配置
1、配置AppId和Apollo Meta Server
在src/main/resources/下建立META-INF目录,建立app.properties
输入:
app.id=pbcs
apollo.meta=http://10.200.5.29:7080
2、配置本地缓存路径
在application.yml中加入:
apollo:
cacheDir: /opt/data/apollo-cache-dir
3、设置内存中的配置项是否保持和页面上的顺序一致
在application.yml中加入:
apollo:
property:
order:
enable: true
4、启动apollo配置中心
在application.yml中加入:
apollo:
bootstrap:
enabled: true
5、添加环境配置
不设置启动会报错:Environment is set to null. Because it is not available in either (1) JVM system property 'env', (2) OS env variable 'ENV' nor (3) property 'env' from the properties InputStream.
如果是jar包可以使用-Denv参数:
java -Denv=DEV -jar abc.jar
6、指定读取yml文件
由于项目用的是application.yml文件,而apollo控制台上既有application.properties也有application.yml,apollo客户端默认是访问.properties文件,需要在代码中指定
1)本地缓存文件pbcs+default+application.properties
#Persisted by DefaultConfig
#Tue Jul 07 13:42:57 CST 2020
hello=world
2)properties文件地址
http://10.200.5.29:7080/configs/pbcs/default/application
返回:
{"appId":"pbcs","cluster":"default","namespaceName":"application","configurations":{"hello":"world"},"releaseKey":"20200707112209-e0f0ea4c19198550"}
3)yml文件地址
http://10.200.5.29:7080/configs/pbcs/default/application.yml
返回:
{"appId":"pbcs","cluster":"default","namespaceName":"application.yml","configurations":{"content":"respCode:\n \"000000\":\n 成功!!!\n \"999999\":\n 失败!!!"},"releaseKey":"20200707163439-75daea4c19198553"}
四、添加测试类
1、修改TestResource.java
package com.example.mycloud.resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfig;
@RestController
public class TestResource {
// @Autowired
// DiscoveryClient discoveryClient; // 服务发现客户端
@Autowired
private Registration registration; // 服务注册
@Value("${hello:未取值}")
private String testValue;
@ApolloConfig("application")
private Config propConfig; // 注入默认的名称空间配置
@ApolloConfig("application.yml")
private Config ymlConfig; // 注入指定的名称空间配置
@RequestMapping("/InstanceInfo")
public String Info() {
String serviceId = registration.getServiceId();
System.out.println("服务id为: " + serviceId);
return registration.getInstanceId();
}
@RequestMapping("/ApolloTest")
public String ApolloTest() {
System.out.println("testValue: " + testValue);
return testValue;
}
@RequestMapping("/ApolloTestYml")
public String ApolloTestYml() {
Config config = ConfigService.getConfig("application.yml");
String someKey = "respCode.000000";
String someDefaultValue = "未定义";
String value = config.getProperty(someKey, someDefaultValue);
System.out.println("value: " + value);
return value;
}
}
2、获取Config有两种方式
//方式一
@ApolloConfig("application")
private Config propConfig; // 注入默认的名称空间配置
@ApolloConfig("application.yml")
private Config ymlConfig; // 注入指定的名称空间配置
//方式二
Config config = ConfigService.getConfig("application.yml");
3、运行mycloud-service-provider1模块的启动类
启动日志:
2020-07-07 16:48:07.837 INFO 37584 --- [ main] c.c.f.f.i.p.DefaultApplicationProvider : App ID is set to pbcs by app.id property from /META-INF/app.properties
2020-07-07 16:48:07.842 INFO 37584 --- [ main] c.c.f.f.i.p.DefaultServerProvider : Environment is set to [DEV] by OS env variable 'ENV'.
2020-07-07 16:48:07.884 INFO 37584 --- [ main] c.c.f.a.i.DefaultMetaServerProvider : Located meta services from apollo.meta configuration: http://10.200.5.29:7080!
2020-07-07 16:48:07.888 INFO 37584 --- [ main] c.c.f.apollo.core.MetaDomainConsts : Located meta server address http://10.200.5.29:7080 for env DEV from com.ctrip.framework.apollo.internals.DefaultMetaServerProvider
2020-07-07 16:48:08.481 INFO 37584 --- [ main] c.e.m.run.ServiceProvider1Application : No active profile set, falling back to default profiles: default
2020-07-07 16:48:09.061 WARN 37584 --- [ main] o.s.boot.actuate.endpoint.EndpointId : Endpoint ID 'service-registry' contains invalid characters, please migrate to a valid format.
2020-07-07 16:48:09.102 INFO 37584 --- [ main] o.s.c.a.ConfigurationClassPostProcessor : Cannot enhance @Configuration bean definition 'com.ctrip.framework.apollo.spring.boot.ApolloAutoConfiguration' since its singleton instance has been created too early. The typical cause is a non-static @Bean method with a BeanDefinitionRegistryPostProcessor return type: Consider declaring such methods as 'static'.
2020-07-07 16:48:09.323 INFO 37584 --- [ main] o.s.cloud.context.scope.GenericScope : BeanFactory id=4949bb0f-77d0-3601-8c58-e961b7b788e7
2020-07-07 16:48:09.341 WARN 37584 --- [ main] o.s.b.c.p.PropertySourcesDeducer : Multiple PropertySourcesPlaceholderConfigurer beans registered [propertySourcesPlaceholderConfigurer, org.springframework.context.support.PropertySourcesPlaceholderConfigurer], falling back to Environment
2020-07-07 16:48:09.724 INFO 37584 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8011 (http)
2020-07-07 16:48:09.747 INFO 37584 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
......省略......
4、执行测试请求地址
1)http://127.0.0.1:8011/ApolloTest
输出:world
2)http://127.0.0.1:8011/ApolloTestYml
输出:value: 成功!!!
五、实例列表
参考资料:
https://github.com/ctripcorp/apollo/wiki/Java客户端使用指南
https://github.com/ctripcorp/apollo/wiki/Apollo核心概念之“Namespace”
https://www.jianshu.com/p/b055b2b87e58
https://blog.csdn.net/zjh_746140129/article/details/86364371
注:最新代码上传至https://github.com/csj50/mycloud