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. dsu on tree学习笔记

    前言 一次模拟赛的\(T3\):传送门 只会\(O(n^2)\)的我就\(gg\)了,并且对于题解提供的\(\text{dsu on tree}\)的做法一脸懵逼. 看网上的其他大佬写的笔记,我自己画 ...

  2. deepin 删除文件后目录不刷新解决方案

    调整最大文件监控数量 sudo vim /etc/sysctl.conf 添加参数 fs.inotify.max_user_watches = 运行使配置生效 sudo /sbin/sysctl -p ...

  3. bagging,random forest,boosting(adaboost、GBDT),XGBoost小结

    Bagging 从原始样本集中抽取训练集.每轮从原始样本集中使用Bootstraping(有放回)的方法抽取n个训练样本(在训练集中,有些样本可能被多次抽取到,而有些样本可能一次都没有被抽中).共进行 ...

  4. PorterDuffXfermode的模式取值

    PorterDuffXfermode(Mode mode) PorterDuff.mode.XXX取值有: 1.PorterDuff.Mode.CLEAR 所绘制不会提交到画布上. 2.PorterD ...

  5. ISO/IEC 9899:2011 条款6.2.1——标识符的作用域

    6.2.1 标识符的作用域 1.一个标识符可以表示一个对象:一个函数:一个结构体.联合体或枚举的一个标签或一个成员,一个typedef名:一个标签名:一个宏名:或一个宏形参.相同的标识符可以在程序中不 ...

  6. 查看linux是几位操作系统

    查看linux是几位操作系统 摘自:https://blog.csdn.net/a34569345/article/details/80179927 2018年05月03日 14:44:44 bill ...

  7. 查看QML数据类型

    assist输入: QML Types A Abstract3DSeries AbstractActionInput AbstractAnimation AbstractAxis AbstractAx ...

  8. 【pep8规范】arc diff 不符合 pep 8 规范

    arc land 的时候,arc报错提示代码不符合pep8规范: 1.单行代码过长(括号中的换行不需要加 /) python代码换行加 / https://blog.csdn.net/codechel ...

  9. Spring Cloud(7):事件驱动(Stream)分布式缓存(Redis)及消息队列(Kafka)

    分布式缓存(Redis)及消息队列(Kafka) 设想一种情况,服务A频繁的调用服务B的数据,但是服务B的数据更新的并不频繁. 实际上,这种情况并不少见,大多数情况,用户的操作更多的是查询.如果我们缓 ...

  10. iOS-宏定义

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAnoAAAPCCAYAAADvRHWgAAAAAXNSR0IArs4c6QAAAZ1pVFh0WE1MOm ...