mgo_config.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. package mgodb
  2. import (
  3. "context"
  4. "eta_gn/eta_chart_lib/utils"
  5. "github.com/qiniu/qmgo"
  6. "github.com/qiniu/qmgo/options"
  7. "go.mongodb.org/mongo-driver/bson"
  8. "go.mongodb.org/mongo-driver/event"
  9. mgoptions "go.mongodb.org/mongo-driver/mongo/options"
  10. "sync"
  11. )
  12. var (
  13. ConnectTimeoutMS = int64(3000)
  14. SocketTimeoutMS = int64(500000)
  15. MaxPoolSize = uint64(50)
  16. MinPoolSize = uint64(0)
  17. )
  18. //func init() {
  19. // fmt.Println("start MgoNewClient")
  20. // MgoNewClient()
  21. // fmt.Println("end MgoNewClient")
  22. //}
  23. type MgoConfig struct {
  24. Host string `json:"host"`
  25. Url string `json:"url"`
  26. Port string `json:"port"`
  27. Username string `json:"username"`
  28. Password string `json:"password"`
  29. AuthSource string `json:"authSource"`
  30. AuthMechanism string `json:"auth_mechanism"`
  31. Database string `json:"database"`
  32. }
  33. // MgoNewClient
  34. // @Description: 创建一个mongodb客户端链接
  35. // @author: Roc
  36. // @datetime 2024-04-25 14:01:14
  37. // @return *qmgo.Client
  38. func MgoNewClient(mgoConfig MgoConfig) *qmgo.Client {
  39. // 创建cmdMonitor,用于打印SQL
  40. //startedCommands := make(map[int64]bson.Raw)
  41. startedCommands := sync.Map{} // map[int64]bson.Raw
  42. cmdMonitor := &event.CommandMonitor{
  43. Started: func(_ context.Context, evt *event.CommandStartedEvent) {
  44. startedCommands.Store(evt.RequestID, evt.Command)
  45. //startedCommands[evt.RequestID] = evt.Command
  46. },
  47. Succeeded: func(_ context.Context, evt *event.CommandSucceededEvent) {
  48. //log.Printf("Command: %v Reply: %v\n",
  49. // startedCommands[evt.RequestID],
  50. // evt.Reply,
  51. //)
  52. var commands bson.Raw
  53. v, ok := startedCommands.Load(evt.RequestID)
  54. if ok {
  55. commands = v.(bson.Raw)
  56. }
  57. //utils.MongoLog.Info("\n【MongoDB】[%.3fms] [%v] %v \n", float64(evt.Duration)/1e6, commands, evt.Reply)
  58. utils.MongoLog.Info("\n【MongoDB】[%.3fms] [%v] \n", float64(evt.Duration)/1e6, commands)
  59. },
  60. Failed: func(_ context.Context, evt *event.CommandFailedEvent) {
  61. //log.Printf("Command: %v Failure: %v\n",
  62. // startedCommands[evt.RequestID],
  63. // evt.Failure,
  64. //)
  65. var commands bson.Raw
  66. v, ok := startedCommands.Load(evt.RequestID)
  67. if ok {
  68. commands = v.(bson.Raw)
  69. }
  70. utils.MongoLog.Info("\n【MongoDB】[%.3fms] [%v] \n %v \n", float64(evt.Duration)/1e6, commands, evt.Failure)
  71. },
  72. }
  73. // 创建options
  74. ops := options.ClientOptions{ClientOptions: &mgoptions.ClientOptions{}}
  75. ops.SetMonitor(cmdMonitor)
  76. ctx := context.Background()
  77. //mongodb+srv://myDatabaseUser:D1fficultP%40ssw0rd@mongodb0.example.com/?authSource=admin&replicaSet=myRepl
  78. //var mongoUrl string
  79. //if mgoConfig.Password != "" {
  80. // mongoUrl = "mongodb://" + mgoConfig.Username + ":" + mgoConfig.Password + "@" +
  81. // mgoConfig.Host + ":" + mgoConfig.Port
  82. //
  83. // if mgoConfig.AuthSource != `` {
  84. // mongoUrl += mongoUrl + "?&authSource=" + mgoConfig.AuthSource
  85. // }
  86. //} else {
  87. // mongoUrl = "mongodb://" + mgoConfig.Host + ":" + mgoConfig.Port
  88. //}
  89. // 创建一个数据库链接
  90. client, err := qmgo.NewClient(ctx, &qmgo.Config{
  91. Uri: mgoConfig.Url,
  92. Auth: &qmgo.Credential{
  93. AuthMechanism: mgoConfig.AuthMechanism,
  94. AuthSource: mgoConfig.AuthSource,
  95. Username: mgoConfig.Username,
  96. Password: mgoConfig.Password,
  97. //PasswordSet: false,
  98. },
  99. Database: mgoConfig.Database,
  100. ConnectTimeoutMS: &ConnectTimeoutMS,
  101. SocketTimeoutMS: &SocketTimeoutMS,
  102. MaxPoolSize: &MaxPoolSize,
  103. MinPoolSize: &MinPoolSize,
  104. }, ops)
  105. if err != nil {
  106. panic("MongoDB连接异常:" + err.Error())
  107. }
  108. return client
  109. }
  110. func MgoGetColl(collName string) (cli *qmgo.QmgoClient, err error) {
  111. ctx := context.Background()
  112. config := &qmgo.Config{
  113. //Uri: MGO_URL,
  114. //Database: MGO_DB,
  115. Coll: collName,
  116. ConnectTimeoutMS: &ConnectTimeoutMS,
  117. SocketTimeoutMS: &SocketTimeoutMS,
  118. MaxPoolSize: &MaxPoolSize,
  119. MinPoolSize: &MinPoolSize,
  120. }
  121. cli, err = qmgo.Open(ctx, config)
  122. return
  123. }