接着这篇:https://www.cnblogs.com/shousiji/p/15271767.html
本文以SGZ.DepartmentService为例
1、打开Consul => Key/Value => Create,以项目名称命名,名称后面加斜杠就是创建文件夹了
2、创建appsettings.Development.json、appsettings.Production.json(就是把项目中的配置文件信息粘贴过来)
3、回到项目,右键appsettings.json,选择“从项目中排除”
4、新建sitesettings.json,配置如下
{ "SiteConfigs": { "ServiceScheme": "http", "ServiceAddress": "192.168.2.119", "ServicePort": 551 }, "ConsulConfigs": { "DataCenter": "dc1", "RegistryAddress": "http://127.0.0.1:8500", "HealthCheckAddress": "/HealthCheck", "ServiceName": "DepartmentService" } }
5、安装Nuget包“Winton.Extensions.Configuration.Consul”
6、Program类的CreateHostBuilder函数改造(应该使用launchSettings.json来配置站点地址,不然用SiteConfigs就多写代码了,留个心眼后面再改造)
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); var configuration = new ConfigurationBuilder().AddJsonFile("sitesettings.json", false, true).Build(); string serviceScheme = configuration["SiteConfigs:ServiceScheme"]; string serviceAddress = configuration["SiteConfigs:ServiceAddress"]; string servicePort = configuration["SiteConfigs:ServicePort"]; if (!string.IsNullOrEmpty(serviceScheme) && !string.IsNullOrEmpty(serviceAddress) && !string.IsNullOrEmpty(servicePort)) { webBuilder.UseUrls($"{serviceScheme}://{serviceAddress}:{servicePort}"); } webBuilder.ConfigureAppConfiguration(configure => { configure.AddConfiguration(configuration); }); #region 从配置中心中获取配置信息,去掉就变为从本地获取 string consulAddress = configuration["ConsulConfigs:RegistryAddress"]; string consulDataCenter = configuration["ConsulConfigs:DataCenter"]; webBuilder.ConfigureAppConfiguration((context, configure) => { IWebHostEnvironment webHostEnvironment = context.HostingEnvironment; string ApplicationName = webHostEnvironment.ApplicationName;// 应用名称 string EnvironmentName = webHostEnvironment.EnvironmentName;// 这个是环境名 configure.AddConsul($"{ApplicationName}/appsettings.{EnvironmentName}.json", options => { options.ConsulConfigurationOptions = c => { c.Datacenter = consulDataCenter; c.Address = new Uri(consulAddress); }; //热加载配置文件 options.ReloadOnChange = true; }); }); #endregion });
7、增加一个action
运行与验证
1、启动项目,访问http://192.168.2.119:551/api/Department/GetString,得到结果
2、项目右键属性->调试,修改环境变量为Production(也可以在launchSettings.json中修改)
3、再启动并访问http://192.168.2.119:551/api/Department/GetString,得到结果
说明确实是从Consul中获取配置,并且可以切换环境
本文代码:https://files.cnblogs.com/files/shousiji/net5_configcenter.rar