当前位置: 移动技术网 > IT编程>开发语言>.net > 使用Topshelf组件构建简单的Windows服务

使用Topshelf组件构建简单的Windows服务

2017年12月08日  | 移动技术网IT编程  | 我要评论

砰砰堂,虚天幻魔,天语u2

 很多时候都在讨论是否需要了解一个组件或者一个语言的底层原理这个问题,其实我个人觉得,对于这个问题,每个人都有自己的看法,个人情况不同,选择的方式也就会不同了。我个人觉得无论学习什么,都应该尝试着去了解对应的原理和源码(这里就不要急着吐槽,容我说完)。对底层的了解不是为了让你写出类似的东西,让你写也不可能写的出来,重写一个就需要以此修改整个底层结构,了解底层知识只是为了让你可以在写业务代码时,选择合适的方式,以此使底层与业务层配合达到效率最佳。任何一种方式有坏有好,需要合适的选择。

  如果觉得楼主以上的说法不对,或者有些不妥,还望见谅,因为争论一个观点没有意义,认为对的人自己会去理解,认为不对的,可以忽略。没有这个必要去花费时间和精力取讨论这种事情。

  以上是扯淡,下面切入正题。前面介绍了一个组件hangfire,用于设置定时任务等等操作,在这里介绍另一款组件topshelf。

一.topshelf组件概述

   topshelf是.net平台的windows服务框架。topshelf可以轻松创建windows服务,测试服务,调试服务,并最终将其安装到windows服务控制管理器(scm)中。topshelf通过允许开发人员专注于服务逻辑,而不是与.net框架中的内置服务支持交互的细节。开发人员不需要了解服务类的复杂细节,通过installutil执行安装,或者了解如何将调试器附加到服务以进行故障排除问题。

   创建windows服务与创建控制台应用程序类似,控制台应用程序创建后,创建一个具有公共start和stop方法的单一服务类。服务操作的方式较多,自动,自动(延迟),手动和禁用启动选项本地系统,本地服务,网络服务,用户名/密码或安装期间提示的服务凭证。服务启动依赖项,包括sql server,msmq和其他具有不同服务名称的多实例服务安装服务恢复选项,包括重新启动,重新引导或运行程序。topshelf与mono合作,可以将服务部署到linux。服务安装功能目前仅限windows。

二.topshelf用法说明

      介绍完对应的组件背景概述,在这里就要介绍一下如何使用这个组件的使用方法。该组件的使用方法有另个方法,都在hostfactory类中,下面具体的介绍一个使用方式。

1.配置新的服务主机

hostfactory.new(x =>
        {
          // 可以定义不需要接口依赖性的服务,这只是为了
          //在此示例中显示并未使用。
          x.service<samplesansinterfaceservice>(s =>
            {
              s.constructusing(() => new samplesansinterfaceservice());
              s.whenstarted(v => v.start());
              s.whenstopped(v => v.stop());
            });
        });

2.配置和运行新的服务主机,处理任何异常并将其写入日志

hostfactory.run(x =>
        {
          x.uselog4net("log4net.config");
          x.useassemblyinfoforserviceinfo();
          bool throwonstart = false;
          bool throwonstop = false;
          bool throwunhandled = false;
          x.service(settings => new sampleservice(throwonstart, throwonstop, throwunhandled), s =>
          {
            s.beforestartingservice(_ => console.writeline("beforestart"));
            s.beforestoppingservice(_ => console.writeline("beforestop"));
          });
          x.setstarttimeout(timespan.fromseconds(10));
          x.setstoptimeout(timespan.fromseconds(10));
          x.enableservicerecovery(r =>
            {
              r.restartservice(3);
              r.runprogram(7, "ping google.com");
              r.restartcomputer(5, "message");

              r.oncrashonly();
              r.setresetperiod(2);
            });
          x.addcommandlineswitch("throwonstart", v => throwonstart = v);
          x.addcommandlineswitch("throwonstop", v => throwonstop = v);
          x.addcommandlineswitch("throwunhandled", v => throwunhandled = v);
          x.onexception((exception) =>
          {
            console.writeline("exception thrown - " + exception.message);
          });
        });

3.topshelf配置操作方法

三.topshelf核心对象解析

承接上文,介绍完毕相关背景和常规操作,在这里介绍一个核心对象的一些方法。

1.hostfactory.new():

public static host new(action<hostconfigurator> configurecallback)
    {
      try
      {
        if (configurecallback == null)
          throw new argumentnullexception("configurecallback");
        var configurator = new hostconfiguratorimpl();
        type declaringtype = configurecallback.method.declaringtype;
        if (declaringtype != null)
        {
          string defaultservicename = declaringtype.namespace;
          if (!string.isnullorempty(defaultservicename))
            configurator.setservicename(defaultservicename);
        }
        configurecallback(configurator);
        configurator.applycommandline();
        configurationresult result = validateconfigurationresult.compileresults(configurator.validate());
        if (result.message.length > 0)
        {
          hostlogger.get(typeof(hostfactory))
               .infoformat("configuration result:\n{0}", result.message);
        }
        return configurator.createhost();
      }
      catch (exception ex)
      {
        hostlogger.get(typeof(hostfactory)).error("an exception occurred creating the host", ex);
        hostlogger.shutdown();
        throw;
      }
    }

该方法用于配置新的服务主机,方法接受一个参数action<hostconfigurator>配置方法调用,该方法返回host对象,表示topshelf服务主机,准备运行。 configurecallback.method.declaringtype;用于获取声明该成员的类。declaringtype.namespace;用于获取获取 system.type 的命名空间。validateconfigurationresult.compileresults(configurator.validate());用于验证配置结果。

2.hostfactory.run():

public static topshelfexitcode run(action<hostconfigurator> configurecallback)
    {
      try
      {
        return new(configurecallback)
          .run();
      }
      catch (exception ex)
      {
        hostlogger.get(typeof(hostfactory))
             .error("the service terminated abnormally", ex);
        hostlogger.shutdown();
        
        return topshelfexitcode.abnormalexit;
      }
    }

该方法是一个静态方法,配置和运行新的服务主机,处理任何异常并将其写入日志。该方法接收一个参数action<hostconfigurator> configurecallback配置方法调用,返回应用程序主方法返回的进程的退出代码。

四.总结

以上是介绍如何使用topshelf组件创建简单的windows服务的方法,在这里只是一个简单的介绍,没有很深入的介绍,如果需要了解更多的东西,可以看源码,毕竟是开源免费的组件,也是一个很不错的组件。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网