golang以服務方式運行

golang開發的二進制程序,通常須要長期後臺運行的,在linux上能夠用supervisor或upstart或systemd等第三方守護進程來實現。其實golang本身也能夠實現以服務的形式常駐後臺。linux

須要的庫

https://github.com/kardianos/servicegit

這個庫裏面有兩個接口定義,一個是:github

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
}

這個接口比較複雜,須要徹底實現接口中的方法,還有一個比較簡單的接口定義:golang

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接口就好了。ide

一個簡單的服務實例:

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方法中實現服務初始化:ui

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 可用於操做服務
如 :this

simple  install   -- 安裝服務
simple  start     -- 啓動服務
simple  stop     -- 中止服務
相關文章
相關標籤/搜索