golang开发的二进制程序,一般需要长期后台运行的,在linux上可以用supervisor或upstart或systemd等第三方守护进程来实现。其实golang自己也可以实现以服务的形式常驻后台。

需要的库

https://github.com/kardianos/service

这个库里面有两个接口定义,一个是:

type Service interface {
// Run should be called shortly after the program entry point.
// After Interface.Stop has finished running, Run will stop blocking.
// After Run stops blocking, the program must exit shortly after.
Run() error // Start signals to the OS service manager the given service should start.
Start() error // Stop signals to the OS service manager the given service should stop.
Stop() error // Restart signals to the OS service manager the given service should stop then start.
Restart() error // Install setups up the given service in the OS service manager. This may require
// greater rights. Will return an error if it is already installed.
Install() error // Uninstall removes the given service from the OS service manager. This may require
// greater rights. Will return an error if the service is not present.
Uninstall() error // Opens and returns a system logger. If the user program is running
// interactively rather then as a service, the returned logger will write to
// os.Stderr. If errs is non-nil errors will be sent on errs as well as
// returned from Logger's functions.
Logger(errs chan<- error) (Logger, error) // SystemLogger opens and returns a system logger. If errs is non-nil errors
// will be sent on errs as well as returned from Logger's functions.
SystemLogger(errs chan<- error) (Logger, error) // String displays the name of the service. The display name if present,
// otherwise the name.
String() string
}

  

这个接口比较复杂,需要完全实现接口中的方法,还有一个比较简单的接口定义:

type Interface interface {
// Start provides a place to initiate the service. The service doesn't not
// signal a completed start until after this function returns, so the
// Start function must not take more then a few seconds at most.
Start(s Service) error // Stop provides a place to clean up program execution before it is terminated.
// It should not take more then a few seconds to execute.
// Stop should not call os.Exit directly in the function.
Stop(s Service) error
}

  

只需要实现Start和Stop接口就行了。

一个简单的服务实例:

type program struct{}
func (p *program) Start(s service.Service) error {
log.Println("开始服务")
go p.run()
return nil
}
func (p *program) Stop(s service.Service) error {
log.Println("停止服务")
return nil
}
func (p *program) run() {
// 这里放置程序要执行的代码……
}

  

之后再main方法中实现服务初始化:

func main(){
//服务的配置信息
cfg := &service.Config{
Name: "simple",
DisplayName: "a simple service",
Description: "This is an example Go service.",
}
// Interface 接口
prg := &program{}
// 构建服务对象
s, err := service.New(prg, cfg)
if err != nil {
log.Fatal(err)
}
// logger 用于记录系统日志
logger, err := s.Logger(nil)
if err != nil {
log.Fatal(err)
}
if len(os.Args) == 2 { //如果有命令则执行
err = service.Control(s, os.Args[1])
if err != nil {
log.Fatal(err)
}
} else { //否则说明是方法启动了
err = s.Run()
if err != nil {
logger.Error(err)
}
}
if err != nil {
logger.Error(err)
}
}

  

使用这以下参数 startstoprestartinstalluninstall 可用于操作服务
如 :

simple  install   -- 安装服务
simple start -- 启动服务
simple stop -- 停止服务

  

golang以服务方式运行的更多相关文章

  1. 以Windows服务方式运行.NET Core程序

    在之前一篇博客<以Windows服务方式运行ASP.NET Core程序>中我讲述了如何把ASP.NET Core程序作为Windows服务运行的方法,而今,我们又遇到了新的问题,那就是: ...

  2. [转帖]以Windows服务方式运行ASP.NET Core程序

    以Windows服务方式运行ASP.NET Core程序 原作者blog: https://www.cnblogs.com/guogangj/p/9198031.htmlaspnet的blog 需要持 ...

  3. [转帖]以Windows服务方式运行.NET Core程序

    以Windows服务方式运行.NET Core程序 原作者blog:https://www.cnblogs.com/guogangj/p/10093102.html 里面使用了NSSM 工具 但是自己 ...

  4. 连表查询都用Left Join吧 以Windows服务方式运行.NET Core程序 HTTP和HTTPS的区别 ASP.NET SignalR介绍 asp.net—WebApi跨域 asp.net—自定义轻量级ORM C#之23中设计模式

    连表查询都用Left Join吧   最近看同事的代码,SQL连表查询的时候很多时候用的是Inner Join,而我觉得对我们的业务而言,99.9%都应该使用Left Join(还有0.1%我不知道在 ...

  5. centos6.x下让redis以服务方式运行

    1.从官网下载redis-2.8.9.tar.gz之后,将redis解压在/usr/local下,目录是redis-2.8.9,然后按照官网给出的办法安装redis即可. 2.安装完在redis-2. ...

  6. 【数据库开发】在Windows上以服务方式运行 MSOPenTech/Redis

    在Windows上以服务方式运行 MSOPenTech/Redis ServiceStack.Redis 使用教程里提到Redis最好还是部署到Linux下去,Windows只是用来做开发环境,现在这 ...

  7. 使用apache daemon让java程序在unix系统上以服务方式运行

    通过使用apache_commons_daemon,可以让Java程序在unix系统上以服务器的方式运行. 当然,通过wrapper也是可以达到这样的目的,wrapper还可以指定java应用中用到的 ...

  8. 如何让msvsmon.exe 以服务方式运行

    通常我们在VS上调试程序用的都是msvsmon.exe, 使用管理员权限运行再选项设置任何人可以调试就可以了,而这个在绝大多数情况下都没有问题.而我想说的就是特殊的情况,跟msvsmon的运行权限相关 ...

  9. Logstash配置以服务方式运行

    Logstash官网最新版下载地址以及YUM源:https://www.elastic.co/cn/downloads/logstash Logstash最常见的运行方式即命令行运行 ./bin/lo ...

随机推荐

  1. springMVC_注解方式搭建基础环境

    ---恢复内容开始--- 一.jar包环境,web配置文件和Spring-MVC配置文件的,相关的modelAndview 1.配置DispatcherServlet <servlet>  ...

  2. 【零基础】神经网络优化之Adam

    一.序言 Adam是神经网络优化的另一种方法,有点类似上一篇中的“动量梯度下降”,实际上是先提出了RMSprop(类似动量梯度下降的优化算法),而后结合RMSprop和动量梯度下降整出了Adam,所以 ...

  3. arcgis python 获得打印机

    class ToolValidator: """Class for validating a tool's parameter values and controllin ...

  4. 【翻译】JNA调用DLL

    一.前言 Jna调用的示范,基本包括了Java->C基本类型的转换,指针的转换等. 不过文章是2011年的,可能后面要查看下有什么改变. 二.原文 http://www.viaboxxsyste ...

  5. PhpStorm 增加Swoole智能提示

    下载https://github.com/eaglewu/swoole-ide-helper的源码 git clone https://github.com/eaglewu/swoole-ide-he ...

  6. 关于Vue.use()详解

    问题 相信很多人在用Vue使用别人的组件时,会用到 Vue.use() .例如:Vue.use(VueRouter).Vue.use(MintUI).但是用 axios时,就不需要用 Vue.use( ...

  7. 微信小程序之分享功能

    说到分享 大家都会想到手机右上角点击不就分享了么?对的没错,那样是分享转发的是小程序  而不是指定的某个页面,所以自己动手丰衣足食,自己写一个转发功能被, 其实也没那么可怕,主要参考的是微信小程序AP ...

  8. Matlab 图像平移、旋转、缩放、镜像

    今天学习了用Matlab实现对图像的基本操作.在Matlab中,图像是按照二维矩阵的形式表示的.所以对图像的操作就是对矩阵的操作. 对图像进行缩放.平移.旋转,都可以转化为矩阵的运算. 关于变换矩阵的 ...

  9. PEP 442 -- Safe object finalization

    https://www.python.org/dev/peps/pep-0442/ PEP 442 -- Safe object finalization PEP: 442 Title: Safe o ...

  10. PorterDuffXfermode之PorterDuff.Mode.LIGHTEN

    package com.loaderman.customviewdemo.view; import android.content.Context; import android.graphics.B ...