Consul配置中心
利用Consul的Key-Value进行做配置中心,进行统一管理及实时更新配置,项目中有时候会用到单例模式,如Redis、ES等,这个时候就需要进行一个通知变化单例模式进行调整
1、首先建立对接Consul配置中心,引入Winton.Extensions.Configuration.Consul,在Program中配置
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }).ConfigureAppConfiguration( builder => { builder .AddConsul( "appsettings.json", options => { options.ConsulConfigurationOptions = cco => { cco.Address = new Uri("http://127.0.0.1:8500"); }; options.ReloadOnChange = true; }).AddConsul("XXXXX.json", o => { o.ConsulConfigurationOptions = cco => { cco.Address = new Uri("http://127.0.0.1:8500"); }; o.ReloadOnChange = true; }) .AddEnvironmentVariables(); }).UseSerilog((context, configuration) => { configuration .ReadFrom.Configuration(context.Configuration) .Enrich.FromLogContext() .WriteTo.Console(); });
2、对IConfiguration进行监听变化,利用ChangeToken进行封装成一个类进行统一处理
public sealed class ConfigHelper { private static IConfiguration _configuration; public static void SetConfiguration(IConfiguration configuration) { _configuration = configuration; } /// <summary> /// 获取配置,可直接获取子级,形式PersonInfo:name" /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <returns></returns> public static T GetAppsetting<T>(string key) { if (_configuration != null) { if (!string.IsNullOrEmpty(key)) { return _configuration.GetSection(key).Get<T>(); } throw new Exception("键不能为空"); } else throw new Exception("Configuration未初始化"); } /// <summary> /// 监听IConfiguration变化 /// </summary> /// <param name="action"></param> public static void ConfigHasChangeSetFunc(Action action) { if (_configuration != null) { ChangeToken.OnChange(() => _configuration.GetReloadToken(), action); } else throw new Exception("Configuration未初始化"); } }