dbhelper.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. fmt.Println(debug)
  38. if debug == "qa" {
  39. fmt.Println("读取QA配置文件成功")
  40. configFileName = fmt.Sprintf("%s-debug.yaml", configFilePrefix)
  41. } else if debug == "uat" {
  42. fmt.Println("读取UAT配置文件成功")
  43. configFileName = fmt.Sprintf("%s-uat.yaml", configFilePrefix)
  44. } else {
  45. fmt.Println("读取PROD配置文件成功")
  46. }
  47. v := viper.New()
  48. v.SetConfigFile(configFileName)
  49. if err := v.ReadInConfig(); err != nil {
  50. log.Fatal("读取配置文件出错:", err)
  51. return nil
  52. }
  53. if err := v.Unmarshal(&conf.MysqlConfig); err != nil {
  54. panic(err)
  55. }
  56. fmt.Println(conf.MysqlConfig)
  57. sourcename := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8",
  58. conf.MysqlConfig.User,
  59. conf.MysqlConfig.Pwd,
  60. conf.MysqlConfig.Host,
  61. conf.MysqlConfig.Port,
  62. conf.MysqlConfig.Datebase)
  63. instance, err := xorm.NewEngine(conf.DriverName, sourcename)
  64. if err != nil {
  65. log.Fatal("dbhelper.NewDbMaster NewEngine error ", err)
  66. return nil
  67. }
  68. //展示执行的sql语句
  69. instance.ShowSQL(true)
  70. masterInstance = instance
  71. return instance
  72. }