zoukankan      html  css  js  c++  java
  • 使用Topshelf创建Windows服务

    一、介绍

    Topshelf是一个开源的跨平台的宿主服务框架,支持Windows和Mono,只需要几行代码就可以构建一个很方便使用的服务宿主。

    Topshelf是创建Windows服务的另一种方。它极大的简化服务创建与部署过程,它支持将控制台应用程序部署为服务。

    下载

    1、官网:http://topshelf-project.com/ 这里面有详细的文档及下载

    2、Topshelf的代码托管在 http://github.com/topshelf/Topshelf/

    二、使用

    1、Topshelf 安装

    通过 NuGet 安装 Topshelf 包。

    Install-Package Topshelf

    image

    2、Topshelf 配置

    以下是我们以 Topshelf 来部署的一个 gRPC 服务代码,Topshelf 关键配置在 Main 方法内,更多的配置建议阅读一下 官方文档

    class Program
    {
      static void Main(string[] args)
      {
        // 配置和运行宿主服务
        HostFactory.Run(x => 
        {
          // 指定服务类型。这里设置为 CacheService
          x.Service<CacheService>(s =>
          {
                    s.ConstructUsing(name => new CacheService());// 通过 new CacheService() 构建一个服务实例 
                    s.WhenStarted(tc => tc.Start());// 当服务启动后执行什么
                    s.WhenStopped(tc => tc.Stop());// 当服务停止后执行什么
          });
                
          x.RunAsLocalSystem();// 服务用本地系统账号来运行,身份标识,有好几种方式,如:x.RunAs("username", "password");  x.RunAsPrompt(); x.RunAsNetworkService(); 等
          
          x.SetDescription("缓存服务");// 服务描述信息      
          x.SetDisplayName("CacheService");// 服务显示名称     
          x.SetServiceName("CacheService"); // 服务名称
        });
      }
    }
    
    public class CacheService
    {
      private readonly string host = ConfigurationManager.AppSettings["Host"];
      private readonly string port = ConfigurationManager.AppSettings["Port"];
    
      readonly Server server;
      public CacheService()
      {
        server = new Server
        {
          Services = { MDCache.BindService(new CacheServiceImpl()) },
          Ports = { new ServerPort(host, Convert.ToInt32(port), ServerCredentials.Insecure) }
        };
      }
      public void Start() { server.Start(); }
      public void Stop() { server.ShutdownAsync(); }
    }

    3、安装服务

    通过以上配置,确保程序集 Build 成功后,进入 binDebug 目录下,执行 install 命令,一个 Windows 服务就诞生了。(如果出现需要以管理员身份启动的提示,重新以管理员身份启动 cmd )。

    xxx.exe install
    

    image

    4、启动服务

    启动:

    xxx.exe start

    也可以安装成功后我们可以在 Windows 服务下找到并启动它。

    image

    注意:因为 serviceName 必须是唯一的,如果我们希望在同一台机器上运行多个相同的服务,那么我们需要注释掉硬编码设置的 ServiceName 和 DisplayName ,然后通过命令参数来动态指定服务名称。

    // 服务显示名称
    //x.SetDisplayName("CacheService");
    // 服务名称
    //x.SetServiceName("CacheService");

    xxx.exe install -servicename cacheService
    xxx.exe install -servicename cacheService1
    

    image

    5、服务卸载

    卸载和启动的命令保持一致,只需要把 install 改成 uninstall 。

    image

    指定服务名称卸载

    image

    三、Service Configuration 服务配置

    以上为自定义模式,还有一种叫简单模式。继承ServiceControl接口,实现该接口即可。

    class Program
    {
        public static void Main(string[] args)
        {
            var logCfg = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config");
            XmlConfigurator.ConfigureAndWatch(logCfg);
    
            HostFactory.Run(x =>
            {
                x.Service<TownCrier>();
                x.RunAsLocalSystem();
    
                x.SetDescription("Sample Topshelf Host服务的描述");
                x.SetDisplayName("Stuff显示名称");
                x.SetServiceName("Stuff服务名称");
            });
        }
    }

    public class TownCrier : ServiceControl
    {
        private Timer _timer = null;
        readonly ILog _log = LogManager.GetLogger(typeof(TownCrier));
        public TownCrier()
        {
            _timer = new Timer(1000) { AutoReset = true };
            _timer.Elapsed += (sender, eventArgs) => _log.Info(DateTime.Now);
    
        }
        public bool Start(HostControl hostControl)
        {
            _log.Info("TopshelfDemo is Started");
            _timer.Start();
            return true;
        }
    
        public bool Stop(HostControl hostControl)
        {
            throw new NotImplementedException();
        }
    }
    
    
  • 相关阅读:
    Python学习札记(十五) 高级特性1 切片
    LeetCode Longest Substring Without Repeating Characters
    Python学习札记(十四) Function4 递归函数 & Hanoi Tower
    single number和变体
    tusen 刷题
    实验室网站
    leetcode 76. Minimum Window Substring
    leetcode 4. Median of Two Sorted Arrays
    leetcode 200. Number of Islands 、694 Number of Distinct Islands 、695. Max Area of Island 、130. Surrounded Regions 、434. Number of Islands II(lintcode) 并查集 、178. Graph Valid Tree(lintcode)
    刷题注意事项
  • 原文地址:https://www.cnblogs.com/springsnow/p/13161809.html
Copyright © 2011-2022 走看看