优雅重启代码
- 测试优雅重启,获取程序版本内容
1.0.7
- 1、老版本代码
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
- 2、新版本代码
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即可上传更新程序进行覆盖。
- 1、通过WinSCP上传新版本的更新程序
- 2、
ps -aux|grep 程序进程名
获取到程序的pid
$ 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
- 3、
kill -USR2 36106
,触发服务器正常重启 - 4、执行新版本测试,通过更改返回内容,校验是否优雅重启成功
curl 127.0.0.1:1321/
1.0.8
保持Windows环境能正常日常开发
因grace仅能在Linux环境开发编译,故需通过系统条件编译使能在Windows环境能够正常开发
- 创建Linux编译文件
start_linux.go
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))
}
- 创建Windows编译文件
start_windows.go
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")
}
网友评论