.netCore3 下利用worker services给应用添加windows(Linux)服务

Worker Services是.netCore3中新增的创建后台服务的方法,它可以将应用部署成windows服务或linux守护程序。给后台开发的攻城师们提供了一个新武器。下面将创建一个基于Nancy的webapi,并给其添加windows(Linux)服务功能。

vs2019创建一个aps.net core web 应用程序的空项目

.netCore3 下利用worker services给应用添加windows(Linux)服务

安装Nuget包

.netCore3 下利用worker services给应用添加windows(Linux)服务

  • Microsoft.AspNetCore.Owin 用Owin技术使程序可以独立运行
  • Nancy 第三方webapi框架
  • Microsoft.Extensions.Hosting.WindowsServices 用于给程序添加worker services的包

新增Hello.cs和Worker.cs文件

  • Hello.cs 用于写webapi相关内容
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Nancy;

namespace Nancy.Test
{
    public class Hello:NancyModule
    {
        public Hello()
        {
            Get("/", r => "Hello,Nancy,i am running on .NET Core 3.0");
            Get("/{name}", r => "你好:" + r.name);

        }
    }
}
  • Worker.cs 用于定义worker services的工作类
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Nancy.Test
{
    public class Worker : BackgroundService
    {
        private readonly ILogger<Worker> _logger;

        public Worker(ILogger<Worker> logger)
        {
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {

            while (!stoppingToken.IsCancellationRequested)
            {
                //_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
                await Task.Delay(1000, stoppingToken);
            }
        }
    }
}

修改 Startup.cs 和 Program.cs 相关内容

  • Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Nancy.Owin;

namespace Nancy.Test
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseOwin(x => x.UseNancy());//启用Nancy

        }
    }
}
  • Program.cs
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Nancy.Test
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>()
                    .UseKestrel(options =>
                    {
                        options.AllowSynchronousIO = true;  //允许同步方式,否则Nancy的同步方法访问异常
                    });
                })
                .UseWindowsService()
                .ConfigureServices((hostContext,services) =>
                {
                    services.AddHostedService<Worker>();//添加windows服务模块
                })
            ;
    }
}

程序发布

dotnet publish  -c Release -o pub

发布后pub文件夹中生成对应的.exe文件

安装为windows服务

  • 使用sc.exe工具创建windows服务,用管理员权限打开命令行。
sc.exe create demoNancyHello binPath=E:\devloper\vs2019\Nancy.Test\Nancy.Test\pub\Nancy.Test.exe

.netCore3 下利用worker services给应用添加windows(Linux)服务

  • 查看windows服务,并启动服务
    .netCore3 下利用worker services给应用添加windows(Linux)服务

    • 删除服务 sc.exe delete demoNancyHello
    • 停止服务 sc.exe stop demoNancyHello
  • 测试一下效果
    .netCore3 下利用worker services给应用添加windows(Linux)服务

部署到Linux

  • 添加Microsoft.Extensions.Hosting.Systemd NuGet包
  • 将UseSystemd()添加到主机构建器中
public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .UseSystemd()  //使用systemd方式,部署linux服务
        .ConfigureServices((hostContext, services) =>
        {
            services.AddHostedService<Worker>();
        });

可以跨平台了。

参考:

.NET Core3.0创建Worker Services
最简明扼要的 Systemd 教程,只需十分钟
systemd创建自定义服务(Ubuntu)

.netCore3 下利用worker services给应用添加windows(Linux)服务

上一篇:C# 读取配置(详细操作,让我们一起共同成长)


下一篇:使用DRF来快速实现API调用服务