前言
最近项目逐步转向基于.Net Core,目前dotnet core 虽然已出3.0了但还没有特别成熟的框架,要实现微服务,必须要解决配置中心的问题 。不管是不是微服务,节点多了配置文件一个个更改非常麻烦,今天分享一个基于Consul 实现轻量级的配置中心方案。
实现思路基于Consul的Key/value ,多个Consul 节点之间可以自动同步配置,我们的程序中就是实现ConfigurationProvider,监听Consul变化
代码
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Winton.Extensions.Configuration.Consul; namespace Bo.ServiceB { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) { var cancellationTokenSource = new CancellationTokenSource(); return WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { var env = hostingContext.HostingEnvironment; hostingContext.Configuration = config.Build(); string consul_url = hostingContext.Configuration["Consul_Url"]; config.AddConsul( $"{env.ApplicationName}/appsettings.{env.EnvironmentName}.json", cancellationTokenSource.Token, options => { options.Optional = true; options.ReloadOnChange = true; options.OnLoadException = exceptionContext => { exceptionContext.Ignore = true; }; options.ConsulConfigurationOptions = cco => { cco.Address = new Uri(consul_url); }; } ).AddEnvironmentVariables(); hostingContext.Configuration = config.Build(); }).UseUrls("http://localhost:5012") .UseStartup<Startup>(); } } }
Consul 中Key/Value 配置:
$"{env.ApplicationName}/appsettings.{env.EnvironmentName}.json",
env.ApplicationName :应用程序名称 如:Bo.ServiceB
env.EnvironmentName: appsettings.Development.json
代码中输出AppName配置:
[HttpGet] public string Get() { return HttpContext.Request.Host.Port + " " + Configuration["AppName"].ToString() + " " + DateTime.Now.ToString(); }
查看多个节点同步情况