main.go 2.5 KB

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