程序员的资源宝库

网站首页 > gitee 正文

Apollo在一般Spring项目的基本使用

sanyeah 2024-03-29 17:44:44 gitee 8 ℃ 0 评论

Apollo(阿波罗)是携程框架部门研发的分布式配置中心,能够集中化管理应用不同环境、不同集群的配置,配置修改后能够实时推送到应用端,并且具备规范的权限、流程治理等特性,适用于微服务配置管理场景。

具体介绍可参照github:https://github.com/ctripcorp/apollo


这是需要添加的依赖。

<!--apollo-->
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-client</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>

图为apollo的页面详情;

 

用户在用java连接apollo时,需要创建app.properties在META-INF的文件夹下,而META-INF必须在resources下面,另外还需要创建aopollo-env.properties。

 

首先介绍app.properties

在apollo配置中心中存在AppId,这是每一个项目的唯一标识,因此app.properties内需要确定,你需要使用哪个项目的配置信息

           

 

       因为apollo在java中也需要远程连接apollo配置信息的数据,因此可以加入apollo.meta={ip}:8080,因为apollo一般是8070的端口,但我们获取数据的端口一般是8080,这个具体需要与运维了解他们的配置的apollo的端口。这种方式也可以获取apollo的具体数据,这似乎我们已经可以连接apollo获取数据了,感觉之前图中的apollo-env.properties,好像没有什么作用了,但是在实际开发中,我们不可能只有一个环境,开发有开发环境,测试有测试环境,生产有生产环境,因此我们一般不会写死apollo.meta,采用中间的图的app.id,不同环境仅是服务器不同,但我们保持app.id一致。

         apollo-env.properties中就是用来配置不同环境访问不同的apollo配置中心的,apollo允许用户配置四个不同的环境,分别是dev-开发环境,fat-功能测试环境,uat-用户测试环境, pro-生产环境。

 

这似乎好像还有一个问题,服务器如何知道自己是处于什么环境因此还需要一个配置告诉apollo自己的电脑是处于什么环境

,因此开发人员需要在C:\opt\settings 的文件夹下配置server.properties,

 

在server.properties中告诉apollo自己在什么环境,

 

 

apollo存在四种环境,如果是开发人员那就老老实实配置DEV环境吧

在能获取到远程配置后,需要配置到spring中才能使用

public class AppPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
try {
//从apollo中获取所有配置信息
Config config = ConfigService.getAppConfig(); //config instance is singleton for each namespace and is never null
Set<String> fieldnames = config.getPropertyNames();
//遍历配置信息
for(String fieldname : fieldnames){
String attributeName=fieldname;
String attributeValue = config.getProperty(fieldname,"");
System.out.println("attributeName:"+attributeName + "; attributeValue:" + attributeValue );
props.put(attributeName,attributeValue);
}
} catch (Exception e) {
e.printStackTrace();
logger.info("获取apollo配置失败");
}

super.processProperties(beanFactoryToProcess, props);
}
}
这样就能将得到的所有配置存储到spring容器中了,不过不要忘了配置xml文件

<!-- 这个是最简单的配置形式,一般应用用这种形式就可以了,用来指示Apollo注入application namespace的配置到Spring环境中 -->
<!--<apollo:config />-->
<apollo:config order="11" />
<bean id="appPropertyPlaceholderConfigurer"
class="com.yudianbank.ApolloConfigCenter.AppPropertyPlaceholderConfigurer"></bean>
至于复杂,有多个namespace的情况,还在学习中,有所了解在记录自己的学习
-----------------------------------------------------------------------------------------------------------

 


来源:CSDN
原文:https://blog.csdn.net/l695914494/article/details/86237150

 

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表