main.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package main
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "gorm.io/driver/mysql"
  5. "gorm.io/gorm"
  6. gormLogger "gorm.io/gorm/logger"
  7. file "iot_manager_service/app/file/dao"
  8. user "iot_manager_service/app/user/dao"
  9. "iot_manager_service/config"
  10. _ "iot_manager_service/config"
  11. "iot_manager_service/router"
  12. "iot_manager_service/util/cache"
  13. "iot_manager_service/util/logger"
  14. "net/url"
  15. "time"
  16. )
  17. func main() {
  18. cfg := config.Instance()
  19. // 只在本地开调试模式
  20. if cfg.Logger.DbShowLog == 1 {
  21. gin.SetMode(gin.DebugMode)
  22. } else {
  23. gin.SetMode(gin.ReleaseMode)
  24. }
  25. logger.InitLog()
  26. // 实例化配置
  27. initDB()
  28. err := cache.InitRedis()
  29. if err != nil {
  30. panic(err)
  31. }
  32. engine := gin.Default()
  33. router.InitRouter(engine)
  34. if cfg.Logger.DbShowLog == 1 {
  35. println(gin.DebugMode + "当前为开发环境,会产生较多调试日志")
  36. } else {
  37. println(gin.ReleaseMode)
  38. }
  39. _ = engine.Run(config.Instance().Server.Address)
  40. }
  41. func initDB() {
  42. cfg := config.Instance()
  43. dsn := cfg.Database.Auth + ":" + cfg.Database.Password + "@tcp(" + cfg.Database.Host + ":" + cfg.Database.Port + ")/" + cfg.Database.Name + "?charset=utf8&parseTime=True" + "&loc=" + url.QueryEscape(cfg.Database.Timezone)
  44. // 如果是本地开发环境 则 打印gorm 查询日志到控制台
  45. logCfg := gormLogger.Interface(nil)
  46. if cfg.Logger.DbShowLog == 1 {
  47. logCfg = gormLogger.Default
  48. } else {
  49. logCfg = gormLogger.New(logger.Logger, gormLogger.Config{
  50. SlowThreshold: 200 * time.Millisecond,
  51. LogLevel: gormLogger.Error,
  52. Colorful: true,
  53. })
  54. }
  55. //logCfg = gormLogger.Default
  56. db, err := gorm.Open(mysql.New(mysql.Config{
  57. DSN: dsn,
  58. }), &gorm.Config{Logger: logCfg})
  59. if err != nil {
  60. panic(err)
  61. } else {
  62. sqlDB, err := db.DB()
  63. if err != nil {
  64. panic(err)
  65. }
  66. if err := sqlDB.Ping(); err != nil {
  67. panic(err)
  68. }
  69. sqlDB.SetMaxOpenConns(32)
  70. sqlDB.SetMaxOpenConns(5)
  71. sqlDB.SetConnMaxLifetime(time.Hour * 4) //括号里面是超时时间,要小于数据库的超时时间 返回 invalid connection的问题
  72. }
  73. user.InitDB(db)
  74. file.InitDB(db)
  75. }