mgo_config.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package mgodb
  2. import (
  3. "context"
  4. "fmt"
  5. "go.mongodb.org/mongo-driver/mongo"
  6. "go.mongodb.org/mongo-driver/mongo/options"
  7. "go.mongodb.org/mongo-driver/mongo/readpref"
  8. "time"
  9. )
  10. var (
  11. MaxPoolSize = uint64(50)
  12. MinPoolSize = uint64(0)
  13. )
  14. //func init() {
  15. // fmt.Println("start MgoNewClient")
  16. // MgoNewClient()
  17. // fmt.Println("end MgoNewClient")
  18. //}
  19. type MgoConfig struct {
  20. Url string `json:"url"`
  21. Username string `json:"username"`
  22. Password string `json:"password"`
  23. AuthMechanism string `json:"auth_mechanism"`
  24. Database string `json:"database"`
  25. }
  26. func NewMgoClient(mgoConfig MgoConfig) *mongo.Client {
  27. var err error
  28. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  29. defer cancel()
  30. credential := options.Credential{
  31. AuthMechanism: mgoConfig.AuthMechanism,
  32. Username: mgoConfig.Username,
  33. Password: mgoConfig.Password,
  34. }
  35. clientOpts := options.Client().ApplyURI(mgoConfig.Url).SetAuth(credential)
  36. /*startedCommands := sync.Map{} // map[int64]bson.Raw
  37. cmdMonitor := &event.CommandMonitor{
  38. Started: func(_ context.Context, evt *event.CommandStartedEvent) {
  39. startedCommands.Store(evt.RequestID, evt.Command)
  40. //startedCommands[evt.RequestID] = evt.Command
  41. },
  42. Succeeded: func(_ context.Context, evt *event.CommandSucceededEvent) {
  43. //log.Printf("Command: %v Reply: %v\n",
  44. // startedCommands[evt.RequestID],
  45. // evt.Reply,
  46. //)
  47. var commands bson.Raw
  48. v, ok := startedCommands.Load(evt.RequestID)
  49. if ok {
  50. commands = v.(bson.Raw)
  51. }
  52. utils.MongoLog.Info("\n【MongoDB】[%.3fms] [%v]\n", float64(evt.Duration)/1e6, commands)
  53. },
  54. Failed: func(_ context.Context, evt *event.CommandFailedEvent) {
  55. //log.Printf("Command: %v Failure: %v\n",
  56. // startedCommands[evt.RequestID],
  57. // evt.Failure,
  58. //)
  59. var commands bson.Raw
  60. v, ok := startedCommands.Load(evt.RequestID)
  61. if ok {
  62. commands = v.(bson.Raw)
  63. }
  64. utils.MongoLog.Info("\n【MongoDB】[%.3fms] [%v] \n %v \n", float64(evt.Duration)/1e6, commands, evt.Failure)
  65. },
  66. }
  67. // 创建options
  68. clientOpts.SetMonitor(cmdMonitor)*/
  69. clientOpts.SetMinPoolSize(MinPoolSize)
  70. clientOpts.SetMaxPoolSize(MaxPoolSize)
  71. clientOpts.SetConnectTimeout(10 * time.Second)
  72. mgoClient, err := mongo.Connect(context.TODO(), clientOpts)
  73. if err != nil {
  74. panic(err)
  75. }
  76. if err = mgoClient.Ping(ctx, readpref.Primary()); err != nil {
  77. panic(err)
  78. }
  79. fmt.Println("Connected to MongoDB!")
  80. return mgoClient
  81. }