Asp.net core中实现自动更新的Option的方法示例
Asp.netcore可以监视json、xml等配置文件的变化,自动刷新内存中的配置内容,但如果想每隔1秒从zookeeper、consul获取最新的配置信息,需要自己实现.
阅读了Asp.netcoreDocument的Customconfigurationprovider,得知只需要实现自己的IConfigurationSource和对应ConfigurationProvider即可
在这个示例中,我建立了一个简单的option,只包含一个不断变化的计数器变量.
publicclassRefreshableOptions { publicintIncreasementCount{get;set;} }
实现IConfigurationSource和对应ConfigurationProvider,内部有一个timer模拟从外部获取了最新的数据,这里为简单起见,采用硬编码的方式指定了option的路径
publicclassAutoRefreshConfigurationSource:IConfigurationSource { publicIConfigurationProviderBuild(IConfigurationBuilderbuilder) { returnnewAutoRefreshConfigurationProvider(); } } publicclassAutoRefreshConfigurationProvider:ConfigurationProvider { privateintcount=0; privateboolisChanged; publicAutoRefreshConfigurationProvider():base() { Timertimer=newTimer(TimerCallback); timer.Change(1000,3000); } publicoverridevoidLoad() { varbeforeData=Data; //这里采用硬编码指定option的路径 Data=newDictionary(){{"AutoRefreshOptions:IncreasementCount",count.ToString()}}; isChanged=IsDictionaryChanged(beforeData,Data); } privatevoidTimerCallback(objectstate) { count++; this.Load(); if(isChanged) { base.OnReload();//通知IConfiguration实例,有参数发生了改变 isChanged=false; } } //判断两个Idictionary是否有不同的帮助方法 privatestaticboolIsDictionaryChanged(IDictionary before,IDictionary after) { if(before==null&&after==null) { returnfalse; } if((before==null)!=(after==null)) { returntrue; } if(before.Count!=after.Count) { returntrue; } varignoreCaseBefore=newDictionary (before,StringComparer.OrdinalIgnoreCase); foreach(varafterItemKeyinafter.Keys) { if(!ignoreCaseBefore.TryGetValue(afterItemKey,outvarbeforeItemValue)) { returntrue; } if(beforeItemValue!=after[afterItemKey]) { returntrue; } ignoreCaseBefore.Remove(afterItemKey); } if(ignoreCaseBefore.Count>0) { returntrue; } returnfalse; } }
实现扩展方法
publicstaticclassAutoRereshConfigurationExtensions { publicstaticIConfigurationBuilderAddAutoRereshConfiguration(thisIConfigurationBuilderbuilder) { returnbuilder.Add(newAutoRefreshConfigurationSource()); } }
使用方法
新建一个WebApi项目,在Program.CreateWebHostBuilder中增加黄色部分
WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration(config=> { config.AddAutoRereshConfiguration(); }) .UseStartup();
在Startup.ConfigureServices中配置
services.Configure(Configuration.GetSection("AutoRefreshOptions"));
修改ValuesController
[Route("api/[controller]")] [ApiController] publicclassValuesController:ControllerBase { privateRefreshableOptionsrefreshableOptions; publicValuesController(IOptionsSnapshotrefreshableOptions) { this.refreshableOptions=refreshableOptions.Value; } [HttpGet] publicActionResult >Get() { returnnewstring[]{"value1","value2",refreshableOptions.IncreasementCount.ToString()}; } }
启动后不停的刷新http://localhost:5000/api/values可以看到返回内容的变化
本文代码
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。