Преглед изворни кода

update:优化一下程序启动的方式

lvxiaorun пре 4 година
родитељ
комит
7c7f482e4e
3 измењених фајлова са 69 додато и 6 уклоњено
  1. 66 3
      app/boot/cmd.go
  2. 2 2
      main.go
  3. 1 1
      passport.yaml

+ 66 - 3
app/boot/cmd.go

@@ -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
+	}
+}

+ 2 - 2
main.go

@@ -1,12 +1,12 @@
 package main
 
 import (
+	"os"
 	_ "passport/config"
 
 	"passport/app/boot"
 )
 
 func main() {
-	boot.Run()
-
+	os.Exit(boot.Run())
 }

+ 1 - 1
passport.yaml

@@ -3,7 +3,7 @@ server:
   port: 10001
 
 mysql:
-  address: shopperthree:U4r6u*j0deCqHN3y@tcp(wzkj.pc:3306)/shopperthree?charset=utf8&parseTime=True&loc=Local
+  address: root:123456@tcp(127.0.0.1:3306)/shopperthree?charset=utf8&parseTime=True&loc=Local
 #  address: tangs:123456@tcp(local.pc:3306)/shopperthree?charset=utf8&parseTime=True&loc=Local
 
 redis: