component.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. package mhayaMongo
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. cfacade "github.com/mhaya/facade"
  7. clog "github.com/mhaya/logger"
  8. cprofile "github.com/mhaya/profile"
  9. "go.mongodb.org/mongo-driver/mongo"
  10. "go.mongodb.org/mongo-driver/mongo/options"
  11. "go.mongodb.org/mongo-driver/mongo/readpref"
  12. )
  13. const (
  14. Name = "mongo_component"
  15. )
  16. type (
  17. Component struct {
  18. cfacade.Component
  19. dbMap map[string]map[string]*mongo.Database
  20. }
  21. // HashDb hash by group id
  22. HashDb func(dbMaps map[string]*mongo.Database) string
  23. )
  24. func NewComponent() *Component {
  25. return &Component{
  26. dbMap: make(map[string]map[string]*mongo.Database),
  27. }
  28. }
  29. func (*Component) Name() string {
  30. return Name
  31. }
  32. func (s *Component) Init() {
  33. // load only the database contained in the `db_id_list`
  34. mongoIdList := s.App().Settings().Get("db_id_list")
  35. if mongoIdList.LastError() != nil || mongoIdList.Size() < 1 {
  36. clog.Warnf("[nodeId = %s] `mongo_id_list` property not exists.", s.App().NodeId())
  37. return
  38. }
  39. mongoConfig := cprofile.GetConfig("mongo")
  40. if mongoConfig.LastError() != nil {
  41. panic("`mongo` property not exists in profile file.")
  42. }
  43. for _, groupId := range mongoConfig.Keys() {
  44. s.dbMap[groupId] = make(map[string]*mongo.Database)
  45. dbGroup := mongoConfig.GetConfig(groupId)
  46. for i := 0; i < dbGroup.Size(); i++ {
  47. item := dbGroup.GetConfig(i)
  48. var (
  49. enable = item.GetBool("enable", true)
  50. id = item.GetString("db_id")
  51. dbName = item.GetString("db_name")
  52. uri = item.GetString("uri")
  53. timeout = time.Duration(item.GetInt64("timeout", 3)) * time.Second
  54. )
  55. for _, key := range mongoIdList.Keys() {
  56. dbId := mongoIdList.Get(key).ToString()
  57. if id != dbId {
  58. continue
  59. }
  60. if !enable {
  61. panic(fmt.Sprintf("[dbName = %s] is disabled!", dbName))
  62. }
  63. db, err := CreateDatabase(uri, dbName, timeout)
  64. if err != nil {
  65. panic(fmt.Sprintf("[dbName = %s] create mongodb fail. error = %s", dbName, err))
  66. }
  67. s.dbMap[groupId][id] = db
  68. clog.Infof("[dbGroup =%s, dbName = %s] is connected.", groupId, id)
  69. }
  70. }
  71. }
  72. }
  73. func CreateDatabase(uri, dbName string, timeout ...time.Duration) (*mongo.Database, error) {
  74. tt := 5 * time.Second
  75. if len(timeout) > 0 && timeout[0].Seconds() > 3 {
  76. tt = timeout[0]
  77. }
  78. // todo tls开启
  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).SetMaxPoolSize(500)
  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. }