.NET Core 3.0之创建基于Consul的Configuration扩展组件(2)

另外,关于Consul的监控主要利用了QueryResult.LastIndex属性,该类缓存了该属性的值,并与实获取的值进行比较,以判断是否需要重新加载内存中的缓存配置

ConsulConfigurationProvider

该类除了实现Load方法外,还会根据ReloadOnChange属性,在构造函数中注册OnChange事件,用于重新加载配置信息,源码如下:

public sealed class ConsulConfigurationProvider : ConfigurationProvider { private readonly ConsulConfigurationParser configurationParser; private readonly IConsulConfigurationSource source; public ConsulConfigurationProvider(IConsulConfigurationSource source, ConsulConfigurationParser configurationParser) { this.configurationParser = configurationParser; this.source = source; if (source.ReloadOnChange) { ChangeToken.OnChange( () => this.configurationParser.Watch(this.source.ServiceKey, this.source.CancellationToken), async () => { await this.configurationParser.GetConfig(true, source).ConfigureAwait(false); Thread.Sleep(source.ReloadDelay); this.OnReload(); }); } } public override void Load() { try { this.Data = this.configurationParser.GetConfig(false, this.source).ConfigureAwait(false).GetAwaiter().GetResult(); } catch (AggregateException aggregateException) { throw aggregateException.InnerException; } } }

调用及运行结果

此处调用在Program中实现

public class Program { public static void Main(string[] args) { CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); WebHost.CreateDefaultBuilder(args).ConfigureAppConfiguration( (hostingContext, builder) => { builder.AddConsul("userservice", cancellationTokenSource.Token, source => { source.ConsulClientConfiguration = cco => cco.Address = new Uri("http://localhost:8500"); source.Optional = true; source.ReloadOnChange = true; source.ReloadDelay = 300; source.QueryOptions = new QueryOptions { WaitIndex = 0 }; }); builder.AddConsul("commonservice", cancellationTokenSource.Token, source => { source.ConsulClientConfiguration = cco => cco.Address = new Uri("http://localhost:8500"); source.Optional = true; source.ReloadOnChange = true; source.ReloadDelay = 300; source.QueryOptions = new QueryOptions { WaitIndex = 0 }; }); }).UseStartup<Startup>().Build().Run(); } }

以上就是本次介绍的全部知识点内容,感谢大家对脚本之家的支持。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wdswxy.html