10

consul系列文章02---替换掉.netcore的配置文件 - zhengwei_cq

 1 year ago
source link: https://www.cnblogs.com/zhengwei-cq/p/16323455.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

consul系列文章02---替换掉.netcore的配置文件

如果是开发微服务的项目,多个服务的配置管理起来比较麻烦,需要集中管理,也就是需要有配置中心:

consul集成配置中心的思路:读取配置文件时不在从本地的应用中读取,而是从consul的KEY/value中读取

集成步骤:

1、首先,安装Consul,具体安装步骤本文就不详细介绍了,请移步我的系列文章01,当打开 http://127.0.0.1:8500 可以看到Consul的UI界面代表安装成功。

2、安装NuGet包:Winton.Extensions.Configuration.Consul

3、Program.cs文件修改

 .ConfigureAppConfiguration((hostingContext, config) =>
               {

                   var cancellationTokenSource = new CancellationTokenSource();

                   var env = hostingContext.HostingEnvironment;
                   hostingContext.Configuration = config.Build();
                   string consul_url = hostingContext.Configuration["Consul_Url"];
                   config.AddConsul(
                               $"{env.ApplicationName}/appsettings.{env.EnvironmentName}.json",
                          
                               options =>
                               {
                                   options.Optional = true;
                                   options.ReloadOnChange = true;
                                   options.OnLoadException = exceptionContext => { exceptionContext.Ignore = true; };
                                   options.ConsulConfigurationOptions = cco => 
                                   { cco.Address = new Uri(consul_url);
                                   };
                               }
                               );

                   hostingContext.Configuration = config.Build();
               })
1109435-20220529110500658-1070161620.png

 4、appsettings.Development.json增加配置

"Consul_Url": "http://192.168.139.129:8500",

5、注入客户端服务类

 context.Services.AddTransient<IConsulClient, ConsulClient>();

6、在consul客户端新建配置文件,也就是将你的配置文件拷贝过来就行了,注意:之前的注释类容在这不可用,要去掉

1109435-20220529110905333-1845611296.png

 7、通过api可以测试一下,看你在consul中修改这个文件后是否有效

我测试后是Ok的,这样就可以替换掉所有的服务配置,将配置文件集中管理起来了


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK