mongodb.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package db
  2. import (
  3. "context"
  4. "encoding/hex"
  5. "fmt"
  6. "mtp2_if/config"
  7. "mtp2_if/packet"
  8. "github.com/qiniu/qmgo"
  9. )
  10. var (
  11. client *qmgo.Client
  12. db *qmgo.Database
  13. ctx context.Context
  14. )
  15. // InitMongoDB 初始化连接MongoDB
  16. func InitMongoDB() error {
  17. // 创建链接
  18. // var err error
  19. // session, err = mgo.Dial(fmt.Sprintf("%s:%d", config.SerCfg.GetMongoDBHostname(), config.SerCfg.GetMongoDBPort()))
  20. // if err != nil {
  21. // return err
  22. // }
  23. // // 选择DB
  24. // mongodb = session.DB(config.SerCfg.GetMongoDBDBName())
  25. // 尝试解密
  26. var dbUser []byte
  27. ciphertext, _ := hex.DecodeString(config.SerCfg.GetMongoDBUsername())
  28. if len(ciphertext) > 8 {
  29. ciphertext = ciphertext[4 : len(ciphertext)-8]
  30. dbUser, _ = packet.Decrypt(ciphertext, packet.AESKey, true)
  31. if dbUser == nil {
  32. dbUser = []byte(config.SerCfg.GetMongoDBUsername())
  33. }
  34. } else {
  35. dbUser = []byte(config.SerCfg.GetMongoDBUsername())
  36. }
  37. var dbPwd []byte
  38. ciphertext, _ = hex.DecodeString(config.SerCfg.GetMongoDBPassword())
  39. if len(ciphertext) > 8 {
  40. ciphertext = ciphertext[4 : len(ciphertext)-8]
  41. dbPwd, _ = packet.Decrypt(ciphertext, packet.AESKey, true)
  42. if dbPwd == nil {
  43. dbPwd = []byte(config.SerCfg.GetMongoDBPassword())
  44. }
  45. } else {
  46. dbPwd = []byte(config.SerCfg.GetMongoDBPassword())
  47. }
  48. // // 登陆
  49. // if err := mongodb.Login(string(dbUser), string(dbPwd)); err != nil {
  50. // return err
  51. // }
  52. var err error
  53. ctx := context.Background()
  54. u := fmt.Sprintf("mongodb://%s:%s@%s:%d/?authSource=%s",
  55. string(dbUser),
  56. string(dbPwd),
  57. config.SerCfg.GetMongoDBHostname(),
  58. config.SerCfg.GetMongoDBPort(),
  59. config.SerCfg.GetMongoDBDBName(),
  60. )
  61. c, err := qmgo.NewClient(ctx, &qmgo.Config{Uri: u})
  62. if err != nil {
  63. return err
  64. }
  65. if err = c.Ping(10); err != nil {
  66. return err
  67. }
  68. client = c
  69. db = client.Database(config.SerCfg.GetMongoDBDBName())
  70. return nil
  71. }
  72. // GetMongoDB 获取MongoDB Database
  73. func GetMongoDB() *qmgo.Database {
  74. return db
  75. }
  76. func GetMongoDBClient() *qmgo.Client {
  77. return client
  78. }
  79. // CloseMongoDB 关闭MongoDB连接
  80. func CloseMongoDB() {
  81. client.Close(ctx)
  82. }