Foreword
Recent projects have gradually shifted based on .Net Core, currently dotnet core While there has been a 3.0 but not yet mature special framework to implement micro-services, we must solve the problem of distribution center. Whether or not the micro-service, multi-node configuration file changes one by one is very troublesome, sharing a distribution center program to achieve lightweight Consul based today.
Consul realization of ideas based on the Key / value, Consul between multiple nodes can automatically synchronize configurations, our program is to achieve ConfigurationProvider, listening Consul change
Code
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 in Key / Value Configuration:
$ "} {env.ApplicationName / appSettings} {env.EnvironmentName .json.",
env.ApplicationName: application name, such as: Bo.ServiceB
env.EnvironmentName: appsettings.Development.json
Output configuration code AppName:
[HttpGet] public string Get() { return HttpContext.Request.Host.Port + " " + Configuration["AppName"].ToString() + " " + DateTime.Now.ToString(); }
View multiple nodes synchronize situation
Source Address: https://github.com/zhangbojr/Consul-key-Value-.git