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. ICEMCFD中,face裂缝修复的小窍门【转载】

    转载自:http://blog.sina.com.cn/s/blog_4a21884b010005ng.html 采用ICEMCFD画网格的初学者,都对由cad(proe/ug/solidworks) ...

  2. 会话技术cookie与session

    目录 会话技术cookie 会话技术 cookie 服务器怎样把Cookie写 给客户端 服务器如何获取客户端携带的cookie session session简介 Session如何办到在一个ser ...

  3. php如何生成 uuid(总结)

    php如何生成 uuid(总结) 一.总结 一句话总结: UUID的全拼为“Universally Unique Identifier”,可以译为“通用唯一识别码”. UUID是指在一台机器上生成的数 ...

  4. Java 代码编写单例模式总结

    手写一个单例模式是 Java 面试中常见的问题,很多时候我们更偏向于简单的写一个饿汉或饱汉模式,深入研究的甚少,这里列举三种实现方式,并对各自的优缺进行分析. 1. 饿汉式 public class ...

  5. SpringBoot视图层技术

    一.SpringBoot整合jsp 在maven的dependencies的依赖中除了springBoot启动器还要添加对jstl和jsp的依赖. <dependencies> <d ...

  6. MySQL格式化时间date_format

    select date_format(deal_date, '%Y年%m月%d日 %H时%i分%s秒'), date_format(deal_date, '%Y-%m-%d %H:%i:%s') fr ...

  7. iOS12 中的后台下载与上传

    严格意义上来说,iOS并不能像Android一样,真的在后台开启一个下载Service,一直下载.但是它可以进行在系统允许范围内的后台上传和下载. 当使用 NSURLSessionConfigurat ...

  8. MongoDB基础笔记

    MongoDB show dbs 查看当前的数据库 use test 选库 show tables/collections 查看当前库下的文档 db.help() 查看帮助 db.createColl ...

  9. zblog文件大小超出,上传成功但插入不了

    在zblogphp时,经常会遇到需要上传2m以上的文件或图片,这个时候就需要修改默认上传文件的大小了.看了很多地方的文章都解决不了,后面在麒麟杰博客找到相关解决办法.   工具/原料   zblogp ...

  10. java调用科大讯飞流式(websocket)语音识别接口

    要使用讯飞的能力,需先注册讯飞开发平台账号(讯飞官网参见https://www.xfyun.cn/). 再创建应用,点击右上角的控制台 -> 创建新应用: 每个应用都有一个appId,由这个ap ...