Golang中使用Echo框架进行优雅重启全流程流程

2020-08-14  本文已影响0人  承诺一时的华丽
优雅重启代码
package main

import (
    "net/http"

    "github.com/facebookgo/grace/gracehttp"
    "github.com/labstack/echo"
)

func main() {
    // Setup
    e := echo.New()
    e.GET("/", func(c echo.Context) error {
        return c.String(http.StatusOK, "1.0.7")
    })
    e.Server.Addr = ":1323"

    // Serve it like a boss
    e.Logger.Fatal(gracehttp.Serve(e.Server))
}
curl 127.0.0.1:1321/
1.0.7
package main

import (
    "net/http"

    "github.com/facebookgo/grace/gracehttp"
    "github.com/labstack/echo"
)

func main() {
    // Setup
    e := echo.New()
    e.GET("/", func(c echo.Context) error {
        return c.String(http.StatusOK, "1.0.8")
    })
    e.Server.Addr = ":1323"

    // Serve it like a boss
    e.Logger.Fatal(gracehttp.Serve(e.Server))
}
Linux编译的程序进行更新

* 注意:当程序服务未kill时,使用FileZilla无法上传更新程序进行覆盖,提示无法启动传输。使用WinSCP即可上传更新程序进行覆盖。

$ ps -aux|grep test-service 
username      36106  0.0  0.1 713912 12516 pts/0    Sl   13:09   0:00 ./test-service
username      37627  0.0  0.0 112732   972 pts/0    S+   13:17   0:00 grep --color=auto test-service
curl 127.0.0.1:1321/
1.0.8

保持Windows环境能正常日常开发

因grace仅能在Linux环境开发编译,故需通过系统条件编译使能在Windows环境能够正常开发

package main

import (
    "github.com/facebookgo/grace/gracehttp"
    "github.com/labstack/echo"
)

// HTTP服务优雅重启
// kill -USR2 pid
func start(e *echo.Echo, port string) {
    e.Server.Addr = port
    // Serve it like a boss
    e.Logger.Fatal(gracehttp.Serve(e.Server))
}

package main

import (
    "context"
    "github.com/labstack/echo"
    "log"
    "os"
    "os/signal"
    "syscall"
    "time"
)

// HTTP服务优雅关闭
// kill -HUP pid
func start(e *echo.Echo, port string) {
    go func() {
        if err := e.Start(port); err != nil {
            e.Logger.Info("shutting down the server")
        }
    }()

    // Wait for interrupt signal to gracefully shutdown the server with
    // a timeout of 10 seconds.
    quit := make(chan os.Signal)
    signal.Notify(quit, syscall.SIGKILL, syscall.SIGHUP, os.Interrupt)
    <-quit
    log.Println("Shutdown Server ...")
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    if err := e.Shutdown(ctx); err != nil {
        e.Logger.Fatal(err)
    }
    log.Println("Server exiting")
}

main.go

package main

import (
    "net/http"

    "github.com/labstack/echo"
)

func main() {
    // Setup
    e := echo.New()
    e.GET("/", func(c echo.Context) error {
        return c.String(http.StatusOK, "1.0.7")
    })
    start(e, ":1323")
}

上一篇下一篇

猜你喜欢

热点阅读