優(yōu)雅重啟代碼
- 測(cè)試優(yōu)雅重啟尤仍,獲取程序版本內(nèi)容
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))
}
- 執(zhí)行老版本測(cè)試
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編譯的程序進(jìn)行更新
* 注意:當(dāng)程序服務(wù)未kill時(shí)沦童,使用FileZilla無法上傳更新程序進(jìn)行覆蓋,提示無法啟動(dòng)傳輸撑教。使用WinSCP即可上傳更新程序進(jìn)行覆蓋朝墩。
- 1、通過WinSCP上傳新版本的更新程序
- 2伟姐、
ps -aux|grep 程序進(jìn)程名
獲取到程序的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
,觸發(fā)服務(wù)器正常重啟 - 4愤兵、執(zhí)行新版本測(cè)試鹿霸,通過更改返回內(nèi)容,校驗(yàn)是否優(yōu)雅重啟成功
curl 127.0.0.1:1321/
1.0.8
保持Windows環(huán)境能正常日常開發(fā)
因grace僅能在Linux環(huán)境開發(fā)編譯秆乳,故需通過系統(tǒng)條件編譯使能在Windows環(huán)境能夠正常開發(fā)
- 創(chuàng)建Linux編譯文件
start_linux.go
package main
import (
"github.com/facebookgo/grace/gracehttp"
"github.com/labstack/echo"
)
// HTTP服務(wù)優(yōu)雅重啟
// 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))
}
- 創(chuàng)建Windows編譯文件
start_windows.go
package main
import (
"context"
"github.com/labstack/echo"
"log"
"os"
"os/signal"
"syscall"
"time"
)
// HTTP服務(wù)優(yōu)雅關(guān)閉
// 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")
}