nats-config-mongo.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package comm
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "os"
  7. "strings"
  8. "go.mongodb.org/mongo-driver/mongo"
  9. "go.mongodb.org/mongo-driver/mongo/options"
  10. )
  11. type MongoDB struct {
  12. Client *mongo.Client
  13. Database *mongo.Database
  14. }
  15. func (db *MongoDB) GetCollection(name string) *mongo.Collection {
  16. return db.Database.Collection(name)
  17. }
  18. func createMongo(mongodns string) (*MongoDB, error) {
  19. start := strings.LastIndex(mongodns, "/")
  20. end := strings.LastIndex(mongodns, "?")
  21. database := mongodns[start+1 : end]
  22. fmt.Println("mongo-format database => ", database)
  23. if len(database) < 1 {
  24. return nil, errors.New("config is not format of mongodb://root:root@172.17.0.1:37017/comm?authSource=admin")
  25. }
  26. clientOptions := options.Client().ApplyURI(mongodns)
  27. // 连接到MongoDB
  28. mgoCli, err := mongo.Connect(context.TODO(), clientOptions)
  29. if err != nil {
  30. panic(err)
  31. }
  32. // 检查连接
  33. err = mgoCli.Ping(context.TODO(), nil)
  34. if err != nil {
  35. panic(err)
  36. }
  37. return &MongoDB{Client: mgoCli, Database: mgoCli.Database(database)}, nil
  38. }
  39. func (bus *NatsBus) NewMongoDBFromConfig(mongoConfKey string, timeout ...interface{}) (*MongoDB, error) {
  40. //mongodb://root:root@172.17.0.1:37017/comm?authSource=admin
  41. mongodns, err := bus.RequestConfig(mongoConfKey)
  42. if err != nil {
  43. return nil, err
  44. }
  45. mongoenv := os.Getenv("MONGO")
  46. if len(mongoenv) > 0 {
  47. mongodns = mongoenv
  48. }
  49. fmt.Println("config mongodns => ", mongodns)
  50. fmt.Println("env mongodns => ", mongodns)
  51. return createMongo(mongodns)
  52. }
  53. func (bus *NatsBus) NewMongoDBFromConfigDev(mongoConfKey string, timeout ...interface{}) (*MongoDB, error) {
  54. //mongodb://root:root@172.17.0.1:37017/comm?authSource=admin
  55. mongodns, err := bus.RequestConfigDev(mongoConfKey)
  56. if err != nil {
  57. return nil, err
  58. }
  59. mongoenv := os.Getenv("MONGO")
  60. if len(mongoenv) > 0 {
  61. mongodns = mongoenv
  62. }
  63. fmt.Println("config mongodns => ", mongodns)
  64. fmt.Println("env mongodns => ", mongodns)
  65. return createMongo(mongodns)
  66. }