.net core 3.1 服务承载【Workservice】 电脑版发表于:2021/2/8 12:02 ![.netcore](https://img.tnblog.net/arcimg/hb/c857299a86d84ee7b26d181a31e58234.jpg ".netcore") >#.net core 3.1 服务承载【Workservice】 [TOC] tn>`NET CORE 3.0`新增了`Worker Services`的新项目模板,可以编写长时间运行的后台服务,并且能轻松的部署成`windows Service`或`linux守护程序`。 目录 ------------ tn>https://www.tnblog.net/hb/article/details/5591 WorkerService优点 ------------ tn>独立部署,多种宿主选择 | 支持模式 | | ------------ | | 控制台 | | Windows Service | | systemd | tn>避免程序池回收问题 Demo ------------ >### 创建WorkService项目 ![](https://img.tnblog.net/arcimg/hb/9dad7577dd2245a6a8363b791222fdc0.png) ![](https://img.tnblog.net/arcimg/hb/ff3076233327451692149ddffa9845a9.png) >### 修改内容 tn>将我们以前的相关内容添加到项目中 ![](https://img.tnblog.net/arcimg/hb/74e52631f89d4a1f8ba02a2f8ab46dbe.png) ```csharp public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) // 获取命令行的参数 .ConfigureHostConfiguration(builder => builder.AddCommandLine(args)) .ConfigureAppConfiguration((context, builder) => builder .AddJsonFile("appsettings.json", false) // 添加不同环境的json .AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json", true) ) .ConfigureServices((hostContext, services) => { var fakeMetricsCollector = new FakeMetricsCollector(); services .AddSingleton<IProcessorMetricsCollector>(fakeMetricsCollector) .AddSingleton<INetworkMetricsCollector>(fakeMetricsCollector) .AddSingleton<IMemoryMetricsCollector>(fakeMetricsCollector) .AddSingleton<IMetricsDeliverer, FakeMetricsDeliverer>() .AddSingleton<IHostedService, Worker>() // 添加配置 .AddOptions() .Configure<MetricsCollectionOptions>(hostContext.Configuration.GetSection("MetricsCollection")); }); ``` ```csharp public class Worker : BackgroundService { private readonly ILogger<Worker> _logger; private readonly IProcessorMetricsCollector _processorMetricsCollector; private readonly INetworkMetricsCollector _networkMetricsCollector; private readonly IMetricsDeliverer _metricsDeliverer; private readonly IMemoryMetricsCollector _memoryMetricsCollector; private readonly IOptions<MetricsCollectionOptions> _optionsAccessor; public Worker( IProcessorMetricsCollector processorMetricsCollector, INetworkMetricsCollector networkMetricsCollector, IMetricsDeliverer metricsDeliverer, IMemoryMetricsCollector memoryMetricsCollector, IOptions<MetricsCollectionOptions> optionsAccessor, ILogger<Worker> logger) { _logger = logger; _processorMetricsCollector = processorMetricsCollector; _networkMetricsCollector = networkMetricsCollector; _metricsDeliverer = metricsDeliverer; _memoryMetricsCollector = memoryMetricsCollector; _optionsAccessor = optionsAccessor; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { try { // 执行的方法 await Callback(); } catch (Exception ex) { _logger.LogError(ex, $"Job {nameof(Worker)} threw an exception!"); } // 间隔的时间 await Task.Delay(_optionsAccessor.Value.CaptureInterval); } } private async Task Callback() { // 通过不同指标获取实例 var performanceMetrics = new PerformanceMetrics() { Memory = _memoryMetricsCollector.GetUsage(), Network = _networkMetricsCollector.GetThroughput(), Processor = _processorMetricsCollector.GetUsage() }; await _metricsDeliverer.DeliverAsync(performanceMetrics); } } ``` >### 测试运行 ![](https://img.tnblog.net/arcimg/hb/76d73f0a5ace46968eda4ff796436d3d.png) 部署到Windows服务运行 ------------ >### 添加相关依赖包 tn>在项目中添加nuget包:`Microsoft.Extensions.Hosting.WindowsServices` ![](https://img.tnblog.net/arcimg/hb/5bf8eca89bf846fd88a3b2250ea745ed.png) >### 添加WindowsService方法 tn>然后在`Program.cs`类,将`UseWindowsService()`添加到`HostBuilder`中去 ```csharp .UseWindowsService() ``` >### 发布项目 ![](https://img.tnblog.net/arcimg/hb/e146826f2f3640c5a52ee31fcd14f134.png) tn>然后在该目录下通过命令窗口发布项目 ```bash dotnet publish -c Release -o C:\WorkerPub ``` ![](https://img.tnblog.net/arcimg/hb/e6da2a0a423f4b54a96588b435db0d8e.png) tn>然后我们到`C:\WorkerPub`目录下查看发布情况。 >### 创建WorkerService服务 tn>然后使用`sc.exe`工具来管理服务,输入一下命令创建为`windows服务` ```bash sc.exe create MyTestService binPath=C:\WorkerPub\WorkerService.exe ``` ![](https://img.tnblog.net/arcimg/hb/5a6e18209e2c4afb9f598486c6b39309.png) tn>查看服务状态使用一下命令 ```bash sc.exe query MyTestService ``` ![](https://img.tnblog.net/arcimg/hb/04b2414145f9433581e8ad85938fe561.png) tn>我们发现我们的服务并未启动,接着我们执行启动命令 ```bash sc.exe start MyTestService ``` ![](https://img.tnblog.net/arcimg/hb/c3d30f591872453d8ef996b227fb790c.png) ![](https://img.tnblog.net/arcimg/hb/e124e03c2f1f4e2cbe19a6ca641ba3cf.png) tn>最后我们不需要服务了可以停止服务,与注销服务 ```bash sc.exe stop MyTestService sc.exe delete MyTestService ``` ![](https://img.tnblog.net/arcimg/hb/94dd33b537f542588fb148922a29b8d5.png) 部署作为Linux守护程序运行 ------------ >部署linux守护程序也是很方便的执行一下两个步骤即可: - 添加`Microsoft.Extensions.Hosting.Systemd` NuGet包到项目中,并告诉你的新Worker,其生命周期由systemd管理! - 将`UseSystemd()`添加到`HostBuilder`中 ```csharp .UseSystemd () ```