首页 > 其他分享 >Hosting 与管道

Hosting 与管道

时间:2023-07-28 20:11:47浏览次数:30  
标签:Get int Hosting System 管道 new using public

Hosting 主机/托管 长时间运行的服务寄宿在托管进程

托管服务==服务托管主机 任何需要在后台长期运行的服务

 

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace ConsoleApp1
{
    public class Sample01
    {
        public class SystemClock : IHostedService
        {
            private Timer _timer;
            //启动服务
            public Task StartAsync(CancellationToken cancellationToken)
            {
                _timer = new Timer(state =>
                {
                    Console.WriteLine($"Current Time:{DateTime.Now.ToLongTimeString()}");
                }, null,0, 1000);

                return Task.CompletedTask;                 //返回
            }
            //停止服务
            public Task StopAsync(CancellationToken cancellationToken)
            {
                _timer?.Dispose();
                return Task.CompletedTask;
            }
        }

        public static void Start()
        {
            var host = new HostBuilder()                         //宿主对象
                .ConfigureServices(collection => collection     //依赖注入框架
                    //.AddHostedService<SystemClock>()          //两种方案都行
                    .AddSingleton<IHostedService,SystemClock>()  //单例模式
                    )        //给容器添加服务
                    
                    .Build();                                //构建了宿主对象
            host.Run();                                       //启动,寄宿在宿主的服务启动
        }
    }
}
host1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace ConsoleApp1
{
    public class Sample02
    {
        /// <summary>
        /// 温度
        /// </summary>
        public interface ITemperatureCollector
        {
            int Get();
        }

        /// <summary>
        /// 湿度
        /// </summary>
        public interface IHumidityCollector
        {
            int Get();
        }

        /// <summary>
        /// 空气质量
        /// </summary>
        public interface IAirQualityCollector
        {
            int Get();
        }

        public class Collector: ITemperatureCollector, IHumidityCollector, IAirQualityCollector
        {
            int ITemperatureCollector.Get()
            {
                var random = new Random();
                return random.Next(0, 100);
            }

            int IHumidityCollector.Get()
            {
                var random = new Random();
                return random.Next(0, 100);
            }

            int IAirQualityCollector.Get()
            {
                var random = new Random();
                return random.Next(0, 100);
            }
        }

        public class AirEnvironmentService : IHostedService
        {
            private readonly ITemperatureCollector _temperatureCollector;
            private readonly IHumidityCollector _humidityCollector;
            private readonly IAirQualityCollector _airQualityCollector;

            private Timer _timer;

            public AirEnvironmentService(
                ITemperatureCollector temperatureCollector,
                IHumidityCollector humidityCollector,
                IAirQualityCollector airQualityCollector
            )
            {
                _temperatureCollector = temperatureCollector;
                _humidityCollector = humidityCollector;
                _airQualityCollector = airQualityCollector;
            }

            public Task StartAsync(CancellationToken cancellationToken)
            {
                _timer = new Timer(state =>
                {
                    Console.WriteLine($"温度:{_temperatureCollector.Get(), -10}" +
                                      $"湿度:{_humidityCollector.Get(), -10}" +
                                      $"空气质量:{_airQualityCollector.Get(), -10}" +
                                      $"时间:{DateTime.Now.ToLongTimeString()}");
                }, null,0, 1000);

                return Task.CompletedTask;
            }

            public Task StopAsync(CancellationToken cancellationToken)
            {
                _timer?.Dispose();
                return Task.CompletedTask;
            }
        }

        public static void Start()
        {
            var collector = new Collector();
            var host = new HostBuilder()
                .ConfigureServices(collection => collection         
                    .AddSingleton<ITemperatureCollector>(collector)   //依赖注入
                    .AddSingleton<IHumidityCollector>(collector)
                    .AddSingleton<IAirQualityCollector>(collector)
                    .AddHostedService<AirEnvironmentService>()
                ).Build();

            host.Run();
        }
    }
}
注入

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;

namespace ConsoleApp1
{
    public class Sample03
    {
        /// <summary>
        /// 温度
        /// </summary>
        public interface ITemperatureCollector
        {
            int Get();
        }

        /// <summary>
        /// 湿度
        /// </summary>
        public interface IHumidityCollector
        {
            int Get();
        }

        /// <summary>
        /// 空气质量
        /// </summary>
        public interface IAirQualityCollector
        {
            int Get();
        }

        public class Collector: ITemperatureCollector, IHumidityCollector, IAirQualityCollector
        {
            int ITemperatureCollector.Get()
            {
                var random = new Random();
                return random.Next(0, 100);
            }

            int IHumidityCollector.Get()
            {
                var random = new Random();
                return random.Next(0, 100);
            }

            int IAirQualityCollector.Get()
            {
                var random = new Random();
                return random.Next(0, 100);
            }
        }

        public class AirEnvironmentOptions   //选项
        {
            public long Interval { get; set; }   //间隔
        }

        public class AirEnvironmentService : IHostedService
        {
            private readonly ITemperatureCollector _temperatureCollector;
            private readonly IHumidityCollector _humidityCollector;
            private readonly IAirQualityCollector _airQualityCollector;
            private readonly AirEnvironmentOptions _options;

            private Timer _timer;

            public AirEnvironmentService(
                ITemperatureCollector temperatureCollector,
                IHumidityCollector humidityCollector,
                IAirQualityCollector airQualityCollector,
                IOptions<AirEnvironmentOptions> options
            )
            {
                _temperatureCollector = temperatureCollector;
                _humidityCollector = humidityCollector;
                _airQualityCollector = airQualityCollector;
                _options = options.Value;
            }

            public Task StartAsync(CancellationToken cancellationToken)
            {
                _timer = new Timer(state =>
                {
                    Console.WriteLine($"温度:{_temperatureCollector.Get(), -10}" +
                                      $"湿度:{_humidityCollector.Get(), -10}" +
                                      $"空气质量:{_airQualityCollector.Get(), -10}" +
                                      $"时间:{DateTime.Now.ToLongTimeString()}");
                }, null,0, _options.Interval);    //通过配置文件读取的数据

                return Task.CompletedTask;
            }

            public Task StopAsync(CancellationToken cancellationToken)
            {
                _timer?.Dispose();
                return Task.CompletedTask;
            }
        }


        //appsettings.json
        //        {
        //  "AirEnvironment": {
        //    "Interval": 1000
        //  },

        //  "Logging": {
        //    "LogLevel": {
        //      "Microsoft.*": "Warning" 
        //    }
        //  } 
        //}
 
 
        public static void Start()
        {
            var collector = new Collector();
            var host = new HostBuilder()

                .ConfigureAppConfiguration(builder => builder.AddJsonFile("appsettings.json"))   //配置托管服务的配置对象,读取配置文件
                .ConfigureServices((context, collection) => collection
                    .AddSingleton<ITemperatureCollector>(collector)
                    .AddSingleton<IHumidityCollector>(collector)
                    .AddSingleton<IAirQualityCollector>(collector)
                    .AddHostedService<AirEnvironmentService>()
                    .AddOptions()                                                              //添加选项
                    .Configure<AirEnvironmentOptions>(                                         //注入选项
                        context.Configuration.GetSection("AirEnvironment"))                    //添加配置节
                ).Build();

            host.Run();
        }


        //PS D:\360MoveData\Users\zzhhpe\Documents\Downloads\8、Hosting与管道\ConsoleApp1> dotnet run /enviroment=production
        public static void Start(string[] args)                                              //配置环境
        {

            var collector = new Collector();
            var host = new HostBuilder()
                 .ConfigureHostConfiguration(builder => builder.AddCommandLine(args))            //配置运行环形
                .ConfigureAppConfiguration((context, builder) => builder
                .AddJsonFile("appsettings.json", false)                                         //false 保证不传参数时不报错
                .AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json", true))   //配置托管服务的配置对象,读取配置文件
                .ConfigureServices((context, collection) => collection
                    .AddSingleton<ITemperatureCollector>(collector)                           //构造函数注入
                    .AddSingleton<IHumidityCollector>(collector)
                    .AddSingleton<IAirQualityCollector>(collector)
                    .AddHostedService<AirEnvironmentService>()
                    .AddOptions()                                                              //添加选项
                    .Configure<AirEnvironmentOptions>(                                         //注入选项
                        context.Configuration.GetSection("AirEnvironment"))                    //添加配置节
                ).Build();

            host.Run();

        }
    }
}
配置
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;

namespace ConsoleApp1
{
    public class Sample03
    {
        /// <summary>
        /// 温度
        /// </summary>
        public interface ITemperatureCollector
        {
            int Get();
        }

        /// <summary>
        /// 湿度
        /// </summary>
        public interface IHumidityCollector
        {
            int Get();
        }

        /// <summary>
        /// 空气质量
        /// </summary>
        public interface IAirQualityCollector
        {
            int Get();
        }

        public class Collector: ITemperatureCollector, IHumidityCollector, IAirQualityCollector
        {
            int ITemperatureCollector.Get()
            {
                var random = new Random();
                return random.Next(0, 100);
            }

            int IHumidityCollector.Get()
            {
                var random = new Random();
                return random.Next(0, 100);
            }

            int IAirQualityCollector.Get()
            {
                var random = new Random();
                return random.Next(0, 100);
            }
        }

        public class AirEnvironmentOptions   //选项
        {
            public long Interval { get; set; }   //间隔
        }

        public class AirEnvironmentService : IHostedService
        {
            private readonly ITemperatureCollector _temperatureCollector;
            private readonly IHumidityCollector _humidityCollector;
            private readonly IAirQualityCollector _airQualityCollector;
            private readonly AirEnvironmentOptions _options;

            private Timer _timer;

            public AirEnvironmentService(
                ITemperatureCollector temperatureCollector,
                IHumidityCollector humidityCollector,
                IAirQualityCollector airQualityCollector,
                IOptions<AirEnvironmentOptions> options
            )
            {
                _temperatureCollector = temperatureCollector;
                _humidityCollector = humidityCollector;
                _airQualityCollector = airQualityCollector;
                _options = options.Value;
            }

            public Task StartAsync(CancellationToken cancellationToken)
            {
                _timer = new Timer(state =>
                {
                    Console.WriteLine($"温度:{_temperatureCollector.Get(), -10}" +
                                      $"湿度:{_humidityCollector.Get(), -10}" +
                                      $"空气质量:{_airQualityCollector.Get(), -10}" +
                                      $"时间:{DateTime.Now.ToLongTimeString()}");
                }, null,0, _options.Interval);    //通过配置文件读取的数据

                return Task.CompletedTask;
            }

            public Task StopAsync(CancellationToken cancellationToken)
            {
                _timer?.Dispose();
                return Task.CompletedTask;
            }
        }


        //appsettings.json
        //        {
        //  "AirEnvironment": {
        //    "Interval": 1000
        //  },

        //  "Logging": {
        //    "LogLevel": {
        //      "Microsoft.*": "Warning" 
        //    }
        //  } 
        //}
 
 
        public static void Start()
        {
            var collector = new Collector();
            var host = new HostBuilder()

                .ConfigureAppConfiguration(builder => builder.AddJsonFile("appsettings.json"))   //配置托管服务的配置对象,读取配置文件
                .ConfigureServices((context, collection) => collection
                    .AddSingleton<ITemperatureCollector>(collector)
                    .AddSingleton<IHumidityCollector>(collector)
                    .AddSingleton<IAirQualityCollector>(collector)
                    .AddHostedService<AirEnvironmentService>()
                    .AddOptions()                                                              //添加选项
                    .Configure<AirEnvironmentOptions>(                                         //注入选项
                        context.Configuration.GetSection("AirEnvironment"))                    //添加配置节
                ).Build();

            host.Run();
        }


        //PS D:\360MoveData\Users\zzhhpe\Documents\Downloads\8、Hosting与管道\ConsoleApp1> dotnet run /enviroment=production
        public static void Start(string[] args)                                              //配置环境
        {

            var collector = new Collector();
            var host = new HostBuilder()
                 .ConfigureHostConfiguration(builder => builder.AddCommandLine(args))            //配置运行环形
                .ConfigureAppConfiguration((context, builder) => builder
                .AddJsonFile("appsettings.json", false)                                         //false 保证不传参数时不报错
                .AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json", true))   //配置托管服务的配置对象,读取配置文件
                .ConfigureServices((context, collection) => collection
                    .AddSingleton<ITemperatureCollector>(collector)                           //构造函数注入
                    .AddSingleton<IHumidityCollector>(collector)
                    .AddSingleton<IAirQualityCollector>(collector)
                    .AddHostedService<AirEnvironmentService>()
                    .AddOptions()                                                              //添加选项
                    .Configure<AirEnvironmentOptions>(                                         //注入选项
                        context.Configuration.GetSection("AirEnvironment"))                    //添加配置节
                ).Build();

            host.Run();

        }
    }
}
环境参数
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.VisualBasic;

namespace ConsoleApp1
{
    public class Sample04
    {
        /// <summary>
        /// 温度
        /// </summary>
        public interface ITemperatureCollector
        {
            int Get();
        }

        /// <summary>
        /// 湿度
        /// </summary>
        public interface IHumidityCollector
        {
            int Get();
        }

        /// <summary>
        /// 空气质量
        /// </summary>
        public interface IAirQualityCollector
        {
            int Get();
        }


        public class Collector: ITemperatureCollector, IHumidityCollector, IAirQualityCollector
        {
            int ITemperatureCollector.Get()
            {
                var random = new Random();
                return random.Next(0, 100);
            }

            int IHumidityCollector.Get()
            {
                var random = new Random();
                return random.Next(0, 100);
            }

            int IAirQualityCollector.Get()
            {
                var random = new Random();
                return random.Next(0, 100);
            }
        }

        public class AirEnvironmentOptions
        {
            public long Interval { get; set; }
        }

        public class AirEnvironmentPublisher
        {
            private const string Template = "温度:{temperature, -10}" +
                                             "湿度:{humidity, -10}" +
                                             "空气质量:{airQuality, -10}" +
                                             "时间:{now}";
            private readonly Action<ILogger, int,int,int,string, Exception> _logAction;
            private readonly ILogger _logger;

            public AirEnvironmentPublisher(ILogger<AirEnvironmentPublisher> logger)
            {
                _logger = logger;
                _logAction = LoggerMessage.Define<int, int, int, string>(LogLevel.Information, 0, Template);
            }

            public void Publish(int temp, int humi, int airq)
            {
                _logAction(_logger, temp, humi, airq, DateTime.Now.ToLongTimeString(), null);
            }
        }

        public class AirEnvironmentService : IHostedService
        {
            private readonly ITemperatureCollector _temperatureCollector;
            private readonly IHumidityCollector _humidityCollector;
            private readonly IAirQualityCollector _airQualityCollector;
            private readonly AirEnvironmentPublisher _publisher;
            private readonly AirEnvironmentOptions _options;

            private Timer _timer;

            public AirEnvironmentService(
                ITemperatureCollector temperatureCollector,
                IHumidityCollector humidityCollector,
                IAirQualityCollector airQualityCollector,
                AirEnvironmentPublisher publisher,
                IOptions<AirEnvironmentOptions> options
            )
            {
                _temperatureCollector = temperatureCollector;
                _humidityCollector = humidityCollector;
                _airQualityCollector = airQualityCollector;
                _publisher = publisher;
                _options = options.Value;
            }

            public Task StartAsync(CancellationToken cancellationToken)
            {
                _timer = new Timer(state =>
                {
                    _publisher.Publish(
                        _temperatureCollector.Get(),
                        _humidityCollector.Get(), 
                        _airQualityCollector.Get());
                }, null,0, _options.Interval);

                return Task.CompletedTask;
            }

            public Task StopAsync(CancellationToken cancellationToken)
            {
                _timer?.Dispose();
                return Task.CompletedTask;
            }
        }

        public static void Start()
        {
            var collector = new Collector();
            var host = new HostBuilder()
                .ConfigureAppConfiguration((context,builder) => builder.AddJsonFile("appsettings.json"))
                .ConfigureServices((context, collection) => collection
                    .AddSingleton<ITemperatureCollector>(collector)
                    .AddSingleton<IHumidityCollector>(collector)
                    .AddSingleton<IAirQualityCollector>(collector)
                    .AddSingleton<AirEnvironmentPublisher>()
                    .AddHostedService<AirEnvironmentService>()
                    .AddOptions()
                    .Configure<AirEnvironmentOptions>(
                        context.Configuration.GetSection("AirEnvironment"))
                )
                .ConfigureLogging(builder => builder.AddConsole())
                .Build();

            host.Run();
        }
    }
}
日志
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace ConsoleApp1
{
    public class Sample05
    {
        public class TestService : IHostedService
        {
            private readonly IHostApplicationLifetime _lifetime;
            private IDisposable _tokenSource;

            public TestService(IHostApplicationLifetime lifetime)
            {
                _lifetime = lifetime;

                _lifetime.ApplicationStarted.Register(() =>
                {
                    Console.WriteLine($"{DateTimeOffset.Now} Application Started");
                });

                _lifetime.ApplicationStopping.Register(() =>
                {
                    Console.WriteLine($"{DateTimeOffset.Now} Application Stopping");
                });

                _lifetime.ApplicationStopped.Register(() =>
                {
                    Console.WriteLine($"{DateTimeOffset.Now} Application Stopped");
                });
            }

            public Task StartAsync(CancellationToken cancellationToken)
            {
                _tokenSource =
                    new CancellationTokenSource(TimeSpan.FromSeconds(3)).Token.Register(_lifetime.StopApplication);
                return Task.CompletedTask;
            }

            public Task StopAsync(CancellationToken cancellationToken)
            {
                _tokenSource?.Dispose();
                return Task.CompletedTask;
            }
        }

        public static void Start()
        {
            var host = new HostBuilder()
                .ConfigureServices(collection => collection
                    .AddHostedService<TestService>())
                    .Build();
            host.Run();
        }
    }
}
开始和停止口令

 

标签:Get,int,Hosting,System,管道,new,using,public
From: https://www.cnblogs.com/zzhpebg/p/17588797.html

相关文章

  • 【Oracle】 管道函数pipelined function简单的使用
    Oracle管道函数pipelinedfunction简单的使用如果在函数(function)中加关键字pipelined,就表明这是一个oracle管道函数,其返回值类型必为集合,体现出来的数据结构类似于表,即可以理解成,使用管道函数可以返回一张查询表,可以是单行数据也可以是多行数据,而不是平常函数返回的单行数据......
  • Linux shell | 竖线管道符号放变量 无法访问'|': 没有那个文件或目录 无法访问'wc':
    工作中遇到一个实际问题,文本编码转换。原始命令:catutf8.log|iconv-c-fUTF-8-tGBK|teegbk.log因为某种(方便修改、方便替换)原因,想把“|iconv-c-fUTF-8-tGBK|”命令这段,想放到变量里,做到一处修改处处生效的效果。pipe="|iconv-c-fUTF-8-tGBK|"catutf......
  • __use_no_semihosting 与调用C库函数冲突
    在已经移植freetype代码(使用了大量的C库函数)中,将printf硬件重定向到串口后,#pragmaimport(__use_no_semihosting_swi)与调用C库函数冲突,错误如下:ERROR:L6915E:Libraryreportserror:__use_no_semihosting_swiwasrequested,but_sys_openwasreferenced勾选Options->Target......
  • C#中可以通过管道流实现多线程之间数据交换
    //Console.WriteLine("=======创建线程=========");//ServerThreadserverThreadInstance=newServerThread(pipeName);//ThreadserverThread=newThread(newThreadStart(serverThreadInstance.run));//serverThread.Start();......
  • redis学习十八:redis管道
    如何优化频繁命令往返造成的性能瓶颈:管道可以一次性发送多条命令给服务端,服务端依次处理完毕后,通过一条响应一次性将结果返回,通过减少客户端与redis的通信次数来实现降低往返延时时间,管道实现的原理是队列,先进先出的特性就保证数据的顺序性。管道定义:pipeline是为了解决rtt往返......
  • Linux 使用 dup2 无法正常重定向管道 tinyhttpd
    项目地址:https://github.com/pphboy/pihttpd文件p_sys.ctinyhttpd是这样写的但是文档是,旧的在前,新在后intdup2(intoldfd,intnewfd);所以是,才能正常输出和输入dup2(1,in_pipe[1]);dup2(0,out_pipe[0]);......
  • 1.6 编写双管道ShellCode后门
    本文将介绍如何将CMD绑定到双向管道上,这是一种常用的黑客反弹技巧,可以让用户在命令行界面下与其他程序进行交互,我们将从创建管道、启动进程、传输数据等方面对这个功能进行详细讲解。此外,本文还将通过使用汇编语言一步步来实现这个可被注入的ShellCode后门,并以此提高代码通用性。......
  • 管道如何实现缺水检测-管道液位传感器
    光电管道传感器是一种有效解决传统机械式传感器低精度和卡死失效问题的新型传感器。同时,它也解决了电容式传感器感度衰减导致的不可控性失效问题。这种传感器利用红外光学组件,通过设计形成感应线路,能够判断水和空气中的光折率不同,从而快速稳定地做出状态判断。光电管道传感器的应用......
  • winform控件开发一之复合控件开发(8)管道(pipe)
    上位机中的管道控件分两种,分别是静态管道和动态管道。静态管道,不显示液体的流动和流动方向,如下所示: 动态管道,可以显示液体的流动速度和流动方向,如下所示: 管道控件的实现方法如下?1、使用label实现一个简单的管道,效果如下: 将label标签的autosize属性设置为false,调整lab......
  • 说说设计模式~管道模式(pipeline)
    说明复合的责任链,类似于管道模式,只要符合条件,说会向下传递,不会终止算法说明按最高优先级去使用,符合就用,不符合就走下一个策略具体链条,有点像pipeline管道模式BlackHandlerip=172.17.0.11RateLimitHandlerheader=is-blackWriteBlackHandlerheader=real-black继承......