main.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. package main
  2. import (
  3. "context"
  4. "net/http"
  5. "os"
  6. "os/signal"
  7. "syscall"
  8. "time"
  9. "mtp2_if/config"
  10. "mtp2_if/db"
  11. "mtp2_if/logger"
  12. "mtp2_if/rediscli"
  13. "mtp2_if/routers"
  14. "github.com/DeanThompson/ginpprof"
  15. "github.com/gin-gonic/gin"
  16. _ "github.com/mattn/go-oci8"
  17. )
  18. func main() {
  19. // 初始化配置
  20. err := config.SerCfg.Init("config/config.xml")
  21. if err != nil {
  22. println("read config file failed:", err)
  23. return
  24. }
  25. // 初始化日志组件
  26. err = logger.Init(config.SerCfg.GetLogSetting())
  27. if err != nil {
  28. println("init logger failed:", err)
  29. return
  30. }
  31. // 初始化数据库引擎
  32. err = db.InitDbEngine()
  33. if err != nil {
  34. logger.GetLogger().Errorf("init db engine failed:", err.Error())
  35. return
  36. }
  37. defer db.Close()
  38. // 初始化Redis客户端
  39. err = rediscli.InitRedisCli()
  40. if err != nil {
  41. logger.GetLogger().Errorf("init redis client failed:", err.Error())
  42. return
  43. }
  44. defer rediscli.CloseReidsClient()
  45. if config.SerCfg.GetDebugMode() {
  46. gin.SetMode(gin.DebugMode)
  47. } else {
  48. gin.SetMode(gin.ReleaseMode)
  49. }
  50. // 设置超时
  51. timeout := 15 * time.Second
  52. // 初始化路由
  53. r := routers.InitRouter()
  54. // doubg模式启用pprof
  55. if config.SerCfg.GetDebugMode() {
  56. dm := r.Group("/debug/pprof")
  57. ginpprof.WrapGroup(dm)
  58. timeout = 60 * time.Second
  59. }
  60. // 声明web服务
  61. webser := &http.Server{
  62. Handler: r,
  63. Addr: config.SerCfg.GetWebListenAddr(),
  64. WriteTimeout: timeout,
  65. ReadTimeout: timeout,
  66. }
  67. cxt, cancel := context.WithCancel(context.Background())
  68. defer cancel()
  69. // 启动服务
  70. c := make(chan struct{}, 1)
  71. go func() {
  72. defer close(c)
  73. if err := webser.ListenAndServe(); err != nil {
  74. logger.GetLogger().Errorf("Start service failed[%s].", err.Error())
  75. c <- struct{}{}
  76. }
  77. }()
  78. // 信号控制
  79. s := make(chan os.Signal, 1)
  80. signal.Notify(s, syscall.SIGINT, syscall.SIGTERM)
  81. select {
  82. case <-s:
  83. logger.GetLogger().Debug("Shutdown service...")
  84. timeCxt, tCancel := context.WithTimeout(cxt, 5*time.Second)
  85. defer tCancel()
  86. if err := webser.Shutdown(timeCxt); err != nil {
  87. logger.GetLogger().Errorf("Shutdown service failed: %s", err.Error())
  88. }
  89. case <-c:
  90. }
  91. signal.Stop(s)
  92. defer close(s)
  93. logger.GetLogger().Debug("Service stopped")
  94. }