component.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. package mhayaMongo
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "fmt"
  6. "time"
  7. cfacade "github.com/mhaya/facade"
  8. clog "github.com/mhaya/logger"
  9. cprofile "github.com/mhaya/profile"
  10. "go.mongodb.org/mongo-driver/mongo"
  11. "go.mongodb.org/mongo-driver/mongo/options"
  12. "go.mongodb.org/mongo-driver/mongo/readpref"
  13. )
  14. const (
  15. Name = "mongo_component"
  16. )
  17. type (
  18. Component struct {
  19. cfacade.Component
  20. dbMap map[string]map[string]*mongo.Database
  21. }
  22. // HashDb hash by group id
  23. HashDb func(dbMaps map[string]*mongo.Database) string
  24. )
  25. func NewComponent() *Component {
  26. return &Component{
  27. dbMap: make(map[string]map[string]*mongo.Database),
  28. }
  29. }
  30. func (*Component) Name() string {
  31. return Name
  32. }
  33. func (s *Component) Init() {
  34. // load only the database contained in the `db_id_list`
  35. mongoIdList := s.App().Settings().Get("db_id_list")
  36. if mongoIdList.LastError() != nil || mongoIdList.Size() < 1 {
  37. clog.Warnf("[nodeId = %s] `mongo_id_list` property not exists.", s.App().NodeId())
  38. return
  39. }
  40. mongoConfig := cprofile.GetConfig("mongo")
  41. if mongoConfig.LastError() != nil {
  42. panic("`mongo` property not exists in profile file.")
  43. }
  44. for _, groupId := range mongoConfig.Keys() {
  45. s.dbMap[groupId] = make(map[string]*mongo.Database)
  46. dbGroup := mongoConfig.GetConfig(groupId)
  47. for i := 0; i < dbGroup.Size(); i++ {
  48. item := dbGroup.GetConfig(i)
  49. var (
  50. enable = item.GetBool("enable", true)
  51. id = item.GetString("db_id")
  52. dbName = item.GetString("db_name")
  53. uri = item.GetString("uri")
  54. timeout = time.Duration(item.GetInt64("timeout", 3)) * time.Second
  55. )
  56. for _, key := range mongoIdList.Keys() {
  57. dbId := mongoIdList.Get(key).ToString()
  58. if id != dbId {
  59. continue
  60. }
  61. if !enable {
  62. panic(fmt.Sprintf("[dbName = %s] is disabled!", dbName))
  63. }
  64. db, err := CreateDatabase(uri, dbName, timeout)
  65. if err != nil {
  66. panic(fmt.Sprintf("[dbName = %s] create mongodb fail. error = %s", dbName, err))
  67. }
  68. s.dbMap[groupId][id] = db
  69. clog.Infof("[dbGroup =%s, dbName = %s] is connected.", groupId, id)
  70. }
  71. }
  72. }
  73. }
  74. func CreateDatabase(uri, dbName string, timeout ...time.Duration) (*mongo.Database, error) {
  75. tt := 3 * time.Second
  76. if len(timeout) > 0 && timeout[0].Seconds() > 3 {
  77. tt = timeout[0]
  78. }
  79. tlsConfig := &tls.Config{
  80. MinVersion: tls.VersionTLS12,
  81. PreferServerCipherSuites: true,
  82. }
  83. o := options.Client().ApplyURI(uri).SetTLSConfig(tlsConfig)
  84. //o := options.Client().ApplyURI(uri)
  85. if err := o.Validate(); err != nil {
  86. return nil, err
  87. }
  88. ctx, cancel := context.WithTimeout(context.Background(), tt)
  89. defer cancel()
  90. client, err := mongo.Connect(ctx, o)
  91. if err != nil {
  92. return nil, err
  93. }
  94. err = client.Ping(context.Background(), readpref.Primary())
  95. if err != nil {
  96. return nil, err
  97. }
  98. clog.Infof("ping db [uri = %s] is ok", uri)
  99. return client.Database(dbName), nil
  100. }
  101. func (s *Component) GetDb(id string) *mongo.Database {
  102. for _, group := range s.dbMap {
  103. for k, v := range group {
  104. if k == id {
  105. return v
  106. }
  107. }
  108. }
  109. return nil
  110. }
  111. func (s *Component) GetHashDb(groupId string, hashFn HashDb) (*mongo.Database, bool) {
  112. dbGroup, found := s.GetDbMap(groupId)
  113. if !found {
  114. clog.Warnf("groupId = %s not found.", groupId)
  115. return nil, false
  116. }
  117. dbId := hashFn(dbGroup)
  118. db, found := dbGroup[dbId]
  119. return db, found
  120. }
  121. func (s *Component) GetDbMap(groupId string) (map[string]*mongo.Database, bool) {
  122. dbGroup, found := s.dbMap[groupId]
  123. return dbGroup, found
  124. }