zoukankan      html  css  js  c++  java
  • 【二】、.net core 3.1 windows服务读取appsetting的步骤

    1、在appsetting里添加节点

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      },
      "MQ": {
        "IP": "127.0.0.1",
        "Port": "61616",
        "UserName": "admin",
        "Password": "admin"
      }
    }

    2、新建一个与之对应的类如下:

        public class MQConfig
        {
            public string IP { get; set; }
            public string Port { get; set; }
            public string UserName { get; set; }
            public string Password { get; set; }
        }

    3、修改Program里的CreateHostBuilder

            public static IHostBuilder CreateHostBuilder(string[] args) =>
                Host.CreateDefaultBuilder(args)
                .UseWindowsService()
                .ConfigureServices((hostContext, services) =>
                    {
                        services.AddHostedService<Worker>();
                        services.Configure<MQConfig>(hostContext.Configuration.GetSection(key: "MQ"));
                    })
                .UseSerilog();

    4、在worker里使用

        public class Worker : BackgroundService
        {
            private readonly ILogger<Worker> _logger;
            private readonly MQConfig _mqConfig;
    
            public Worker(ILogger<Worker> logger, IOptions<MQConfig> settings)
            {
                _logger = logger;
                _mqConfig = settings.Value;
            }
    
            protected override async Task ExecuteAsync(CancellationToken stoppingToken)
            {
                while (!stoppingToken.IsCancellationRequested)
                {
                    _logger.LogInformation("Worker running at: {time}" + "IP:{1},Port:{2}", DateTimeOffset.Now, _mqConfig.IP, _mqConfig.Port);
                    await Task.Delay(1000, stoppingToken);
                }
            }
        }

    4、结果如下:

      示例代码地址:https://download.csdn.net/download/jiancaixing/20629212

  • 相关阅读:
    On the fly test
    Spec Explorer 工具学习
    C# Static修饰符的作用
    [转]C#静态方法与非静态方法的比较
    如何获取网站服务器运行状态
    C#快速整理代码格式
    UI auto程序结构组织方式
    TestClass必须是public的
    VS2012如何显示行号
    Error: member names cannot be the same as their enclosing type
  • 原文地址:https://www.cnblogs.com/wjx-blog/p/15075669.html
Copyright © 2011-2022 走看看