在微服务项目中,随着微服务数量的增加,统一修改配置时需要逐个修改并发布会非常繁琐。引入Apollo进行所有配置项的统一管理。
Apollo(阿波罗)是携程框架部门研发的开源配置管理中心,能够集中化管理应用不同环境,不同集群的配置,修改后能够实时推送到应用端,并具备规范的权限,流程治理等特性。
一.Apollo安装:
docker-compose部署
准备好配置文件:
![](https://img2020.cnblogs.com/blog/783110/202103/783110-20210325113527370-1305902865.png)
![](https://img2020.cnblogs.com/blog/783110/202103/783110-20210325113645753-1089374636.png)
cd进入存放配置文件的文件夹,这里起名“Apollo”
输入:docker-compose up -d
![](https://img2020.cnblogs.com/blog/783110/202103/783110-20210325113707512-2030801391.png)
可能遇到以下问题:
Cannot open self /usr/local/bin/docker-compose or archive /usr/local/bin/docker-compose.pkg
解决方法:
wget https://github.com/docker/compose/releases/download/1.25.0/docker-compose-$(uname -s)-$(uname -m) -O /usr/local/bin/docker-compose
安装完成后:
![](https://img2020.cnblogs.com/blog/783110/202103/783110-20210325113734645-1532595375.png)
浏览器访问18070端口
![](https://img2020.cnblogs.com/blog/783110/202103/783110-20210325113808502-903290850.png)
账号:apollo 密码:admin 首页如下图:
![](https://img2020.cnblogs.com/blog/783110/202103/783110-20210325113908351-688066489.png)
二.Apollo使用:
(1)创建WebApi项目 ServiceApi
![](https://img2020.cnblogs.com/blog/783110/202103/783110-20210325114040605-579982991.png)
(2)Nuget包:
Com.Ctrip.Framework.Apollo.Configuration
(3)修改配置
appsettings.json
1 "Apollo": { 2 "AppId": "MicroServiceAppId", 3 "Env": "DEV", 4 "MetaServer": "http://192.168.0.113:18080/", 5 "ConfigServer": [ "http://192.168.0.113:18080/" ] 6 }
其中 192.168.0.113是linux对应的服务器地址
Program.cs
1 public static IHostBuilder CreateHostBuilder(string[] args) => 2 Host.CreateDefaultBuilder(args) 3 .ConfigureAppConfiguration((hostBuilderContext, configurationBuilder) => 4 { 5 LogManager.UseConsoleLogging(Com.Ctrip.Framework.Apollo.Logging.LogLevel.Trace); 6 configurationBuilder 7 .AddApollo(configurationBuilder.Build().GetSection("apollo")) 8 .AddDefault() 9 .AddNamespace("MicroServiceJson", ConfigFileFormat.Json)//自定义的private NameSpace 10 .AddNamespace(ConfigConsts.NamespaceApplication);//Apollo中默认NameSpace的名称 11 }) 12 .ConfigureWebHostDefaults(webBuilder => 13 { 14 webBuilder.UseStartup<Startup>(); 15 });
(4)在Apollo中配置Json命名空间
“添加Namespace”
![](https://img2020.cnblogs.com/blog/783110/202103/783110-20210325114240329-1273918556.png)
配置AppID
![](https://img2020.cnblogs.com/blog/783110/202103/783110-20210325114315391-240459327.png)
创建私有命名空间“MicroServiceJson”,和项目中的配置项对应
![](https://img2020.cnblogs.com/blog/783110/202103/783110-20210325114451971-705248865.png)
配置文本内容,以下是appsettings.json内容,添加测试节点“ApolloTestOption”
![](https://img2020.cnblogs.com/blog/783110/202103/783110-20210325114541991-1619497471.png)
点击按钮“发布”,配置文件发布成功并生效
(5)代码调试:
Summaries[0] = configuration["ApolloTestOption:NameA"];
结果如下:
![](https://img2020.cnblogs.com/blog/783110/202103/783110-20210325114646661-519814338.png)
以上仅用于总结和学习!