.net core 3.1 服务承载【配置选项】 电脑版发表于:2021/2/4 11:32 ![.netcore](https://img.tnblog.net/arcimg/hb/c857299a86d84ee7b26d181a31e58234.jpg ".netcore") >#.net core 3.1 服务承载【配置选项】 [TOC] 目录 ------------ tn>https://www.tnblog.net/hb/article/details/5591 配置选项 ------------ >### 承载配置 tn>应用开发总是会用到配置选项的,如在上一篇文章中性能指标采集的时间间隔就应该使用配置选项的方式来指定。由于涉及对性能指数数据的发送,所以最好将发送的目标地址定义在配置选项中。如果有多种传输协议可供选择,就可以定义相应的配置选项。.NET Core应用推荐采用 `Options` 模式来使用配置选项,所以可以定义如下这个 `MetricsCollectionOptions` 类型来承载`3`种配置选项。 ![](https://img.tnblog.net/arcimg/hb/3b7b8ff6e7f840f6a066f7e7d0da3c73.png) ```csharp public class Endpoint { public string Host { get; set; } public int Port { get; set; } public override string ToString() => $"{Host}:{Port}"; } public class MetricsCollectionOptions { public TimeSpan CaptureInterval { get; set; } public TransportType Transport { get; set; } public Endpoint DeliverTo { get; set; } } public enum TransportType { Tcp, Http, Udp } ``` >### 获取传输协议与目的地址指标 tn>传输协议和目标地址在 `FakeMetricsDeliverer` 服务种,所以我们对它进行了相应的改写。如下面的代码片段所示,我们在构建函数种通过注入的 `IOptions<MetricsCollectionOptions>` 服务来提供上面的两个配置选项.在实现的 `DeliverAsync` 方法中,可以将采用的传输协议与目的地址输出到控制台上。 ```csharp public class FakeMetricsDeliverer : IMetricsDeliverer { private readonly TransportType _transport; private readonly Endpoint _deliverTo; public FakeMetricsDeliverer(IOptions<MetricsCollectionOptions> optionsAccessor) { var options = optionsAccessor.Value; _transport = options.Transport; _deliverTo = options.DeliverTo; } public Task DeliverAsync(PerformanceMetrics performanceMetrics) { Console.WriteLine($"[{DateTimeOffset.Now}]Deliver performance counter {performanceMetrics} to {_deliverTo} via {_transport}"); return Task.CompletedTask; } } ``` >### 设置采集指标频率 tn>与 `FakeMetricsDeliverer` 提取配置选项类似,在承载服务类型 `PerformanceMetricsCollector` 中同样可以采用 `Options` 模式来提供表示性能指标柴鸡的频率配置选项。如下所示的代码片段是 `PerformanceMetricsCollector` 采用配置选项后的完整定义。 ```csharp public sealed class PerformanceMetricsCollector : IHostedService { private readonly IProcessorMetricsCollector _processorMetricsCollector; private readonly INetworkMetricsCollector _networkMetricsCollector; private readonly IMetricsDeliverer _metricsDeliverer; private readonly IMemoryMetricsCollector _memoryMetricsCollector; private readonly IOptions<MetricsCollectionOptions> _optionsAccessor; private IDisposable _scheduler; public PerformanceMetricsCollector( IProcessorMetricsCollector processorMetricsCollector, INetworkMetricsCollector networkMetricsCollector, IMetricsDeliverer metricsDeliverer, IMemoryMetricsCollector memoryMetricsCollector, IOptions<MetricsCollectionOptions> optionsAccessor ) { _processorMetricsCollector = processorMetricsCollector; _networkMetricsCollector = networkMetricsCollector; _metricsDeliverer = metricsDeliverer; _memoryMetricsCollector = memoryMetricsCollector; _optionsAccessor = optionsAccessor; } /// <summary> /// 启动服务 /// </summary> /// <param name="cancellationToken"></param> /// <returns></returns> public Task StartAsync(CancellationToken cancellationToken) { // 需要调用的方法 需要传入的对象 多久后启动 间隔时长执行一次 _scheduler = new Timer(Callback,null,TimeSpan.FromSeconds(5),_optionsAccessor.Value.CaptureInterval); return Task.CompletedTask; } private async void Callback(object state) { // 通过不同指标获取实例 var performanceMetrics = new PerformanceMetrics() { Memory = _memoryMetricsCollector.GetUsage(), Network = _networkMetricsCollector.GetThroughput(), Processor = _processorMetricsCollector.GetUsage() }; await _metricsDeliverer.DeliverAsync(performanceMetrics); } /// <summary> /// 关闭服务 /// </summary> /// <param name="cancellationToken"></param> /// <returns></returns> public Task StopAsync(CancellationToken cancellationToken) { _scheduler?.Dispose(); return Task.CompletedTask; } } ``` >### 创建配置文件 tn>创建`appsetting.json`的配置文件,并将配置文件的设置为`Copy always`。 ![](https://img.tnblog.net/arcimg/hb/1885402cab0448e5a6d1f6955b42824e.png) ![](https://img.tnblog.net/arcimg/hb/8fcfcbedd2fc460392bbfca2c26cbd0c.png) ```json { "MetricsCollection": { "CaptureInterval": "00:00:10", "Transport": "Udp", "DeliverTo": { "Host": "127.0.0.1", "Port": "22" } } } ``` >### 注册配置文件 tn>将`appsetting.json`注册到程序中,并添加上`AddOptions`扩展方法注册 `Options` 模式所需要的核心服务,然后调用`Configure<TOptions>`扩展方法从提供的 `HostBuilderContext` 对象中提取出当前应用的配置,并将它和对应的配置选项类型 `MetricsCollectionOptions` 做了绑定。输出程序后如下图所示: ```csharp var fakeMetricsCollector = new FakeMetricsCollector(); new HostBuilder() .ConfigureAppConfiguration(builder=>builder.AddJsonFile("appsetting.json")) .ConfigureServices((context,svcs) => svcs .AddSingleton<IProcessorMetricsCollector>(fakeMetricsCollector) .AddSingleton<INetworkMetricsCollector>(fakeMetricsCollector) .AddSingleton<IMemoryMetricsCollector>(fakeMetricsCollector) .AddSingleton<IMetricsDeliverer, FakeMetricsDeliverer>() .AddSingleton<IHostedService, PerformanceMetricsCollector>() // 添加配置 .AddOptions() .Configure<MetricsCollectionOptions>(context.Configuration.GetSection("MetricsCollection")) ) .Build() .Run(); ``` ![](https://img.tnblog.net/arcimg/hb/f837e28585c94163a2336ce80159e85e.png)