dbhelper.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. * @description:
  3. * @Author: CP
  4. * @Date: 2020-08-20 22:25:17
  5. * @FilePath: \construction_management\datasource\dbhelper.go
  6. */
  7. package datasource
  8. import (
  9. "fmt"
  10. "log"
  11. "sync"
  12. _ "github.com/go-sql-driver/mysql"
  13. "github.com/go-xorm/xorm"
  14. "github.com/spf13/viper"
  15. "go.mod/conf"
  16. "go.mod/web/utils"
  17. )
  18. //互斥锁
  19. var dbLock sync.Mutex
  20. var masterInstance *xorm.Engine
  21. //单例模式
  22. func InstanceDbMaster() *xorm.Engine {
  23. if masterInstance != nil {
  24. return masterInstance
  25. }
  26. dbLock.Lock()
  27. defer dbLock.Unlock()
  28. if masterInstance != nil {
  29. return masterInstance
  30. }
  31. return NewDbMaster()
  32. }
  33. func NewDbMaster() *xorm.Engine {
  34. debug := utils.GetEnvInfo("DEBUG")
  35. configFilePrefix := "config"
  36. configFileName := fmt.Sprintf("%s-pro.yaml", configFilePrefix)
  37. if debug == "qa" || debug == "mbp" {
  38. fmt.Println("读取QA配置文件成功")
  39. configFileName = fmt.Sprintf("%s-debug.yaml", configFilePrefix)
  40. } else if debug == "uat" {
  41. fmt.Println("读取UAT配置文件成功")
  42. configFileName = fmt.Sprintf("%s-uat.yaml", configFilePrefix)
  43. } else {
  44. fmt.Println("读取PROD配置文件成功")
  45. }
  46. v := viper.New()
  47. v.SetConfigFile(configFileName)
  48. if err := v.ReadInConfig(); err != nil {
  49. log.Fatal("读取配置文件出错:", err)
  50. return nil
  51. }
  52. if err := v.Unmarshal(&conf.MysqlConfig); err != nil {
  53. panic(err)
  54. }
  55. fmt.Println(conf.MysqlConfig)
  56. sourcename := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8",
  57. conf.MysqlConfig.User,
  58. conf.MysqlConfig.Pwd,
  59. conf.MysqlConfig.Host,
  60. conf.MysqlConfig.Port,
  61. conf.MysqlConfig.Datebase)
  62. instance, err := xorm.NewEngine(conf.DriverName, sourcename)
  63. if err != nil {
  64. log.Fatal("dbhelper.NewDbMaster NewEngine error ", err)
  65. return nil
  66. }
  67. //展示执行的sql语句
  68. instance.ShowSQL(true)
  69. masterInstance = instance
  70. return instance
  71. }