|
@@ -3,6 +3,10 @@ package boot
|
|
|
import (
|
|
|
"fmt"
|
|
|
"net/http"
|
|
|
+ "os"
|
|
|
+ "os/signal"
|
|
|
+ "syscall"
|
|
|
+ "time"
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
"github.com/gomodule/redigo/redis"
|
|
@@ -15,14 +19,20 @@ import (
|
|
|
"passport/logger"
|
|
|
)
|
|
|
|
|
|
-func Run() {
|
|
|
+const (
|
|
|
+ // gracefulTimeout controls how long we wait before forcefully terminating
|
|
|
+ gracefulTimeout = 3 * time.Second
|
|
|
+)
|
|
|
+
|
|
|
+func Run() int {
|
|
|
var err error
|
|
|
StoreInit()
|
|
|
err = InitModel()
|
|
|
if err != nil {
|
|
|
panic(err)
|
|
|
}
|
|
|
- StartServer()
|
|
|
+ go StartHttpServer()
|
|
|
+ return handleSignals()
|
|
|
}
|
|
|
|
|
|
//初始化相关必要持久化服务
|
|
@@ -79,7 +89,7 @@ func StoreInit() {
|
|
|
}
|
|
|
|
|
|
//启动服务
|
|
|
-func StartServer() {
|
|
|
+func StartHttpServer() {
|
|
|
//
|
|
|
r := gin.Default()
|
|
|
router.StepRouters(r)
|
|
@@ -88,3 +98,56 @@ func StartServer() {
|
|
|
logger.Info(fmt.Sprintf("Http Server has been started. http://%s", addr))
|
|
|
logger.Fatal("start http server", zap.Error(http.ListenAndServe(addr, r)))
|
|
|
}
|
|
|
+
|
|
|
+func handleSignals() int {
|
|
|
+ signalCh := make(chan os.Signal, 4)
|
|
|
+ signal.Notify(signalCh, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)
|
|
|
+
|
|
|
+WAIT:
|
|
|
+ // Wait for a signal
|
|
|
+ var sig os.Signal
|
|
|
+ select {
|
|
|
+ case s := <-signalCh:
|
|
|
+ sig = s
|
|
|
+ }
|
|
|
+ //log.Info(fmt.Sprintf("Caught signal: %v", sig))
|
|
|
+
|
|
|
+ // Check if this is a SIGHUP
|
|
|
+ if sig == syscall.SIGHUP {
|
|
|
+ //重新加载配置
|
|
|
+ goto WAIT
|
|
|
+ }
|
|
|
+
|
|
|
+ // Check if we should do a graceful leave
|
|
|
+ graceful := false
|
|
|
+ if sig == syscall.SIGTERM || sig == os.Interrupt {
|
|
|
+ graceful = true
|
|
|
+ }
|
|
|
+
|
|
|
+ // Fail fast if not doing a graceful leave
|
|
|
+ if !graceful {
|
|
|
+ return 1
|
|
|
+ }
|
|
|
+
|
|
|
+ // Attempt a graceful leave
|
|
|
+ gracefulCh := make(chan struct{})
|
|
|
+
|
|
|
+ //log.Info("Gracefully shutting down...")
|
|
|
+ go func() {
|
|
|
+ //if err := c.Sys.Leave(); err != nil {
|
|
|
+ // log.Error(fmt.Sprintf("Error: %s", err))
|
|
|
+ // return
|
|
|
+ //}
|
|
|
+ close(gracefulCh)
|
|
|
+ }()
|
|
|
+
|
|
|
+ // Wait for leave or another signal
|
|
|
+ select {
|
|
|
+ case <-signalCh:
|
|
|
+ return 1
|
|
|
+ case <-time.After(gracefulTimeout):
|
|
|
+ return 1
|
|
|
+ case <-gracefulCh:
|
|
|
+ return 0
|
|
|
+ }
|
|
|
+}
|