component.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package mdb
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "github.com/go-redis/redis/v8"
  6. mhayaMongo "github.com/mhaya/components/mongo"
  7. clog "github.com/mhaya/logger"
  8. cactor "github.com/mhaya/net/actor"
  9. cprofile "github.com/mhaya/profile"
  10. "go.mongodb.org/mongo-driver/mongo"
  11. "strings"
  12. )
  13. type ActorDB struct {
  14. cactor.Base
  15. Name string
  16. }
  17. var (
  18. MDB *mongo.Database
  19. RDB redis.UniversalClient
  20. )
  21. func (p *ActorDB) AliasID() string {
  22. return "database" + p.Name
  23. }
  24. // OnInit Actor初始化前触发该函数
  25. func (p *ActorDB) OnInit() {
  26. mongo := p.App().Find(mhayaMongo.Name).(*mhayaMongo.Component)
  27. if mongo == nil {
  28. clog.DPanicf("[component = %s] not found.", mhayaMongo.Name)
  29. }
  30. // 获取 db_id = "center_db_1" 的配置
  31. dbID := p.App().Settings().GetConfig("db_id_list").GetString("game_db_id")
  32. MDB = mongo.GetDb(dbID)
  33. if MDB == nil {
  34. clog.Panic("game_db_id not found")
  35. }
  36. redisConfig := cprofile.GetConfig("redis")
  37. tlsEnable := redisConfig.GetInt("tls")
  38. if tlsEnable == 1 {
  39. tlsConfig := &tls.Config{
  40. MinVersion: tls.VersionTLS12,
  41. PreferServerCipherSuites: true,
  42. }
  43. RDB = redis.NewUniversalClient(&redis.UniversalOptions{
  44. Addrs: strings.Split(redisConfig.GetString("address"), ","),
  45. Password: redisConfig.GetString("password"),
  46. DB: redisConfig.GetInt("database"),
  47. TLSConfig: tlsConfig,
  48. })
  49. } else {
  50. RDB = redis.NewUniversalClient(&redis.UniversalOptions{
  51. Addrs: strings.Split(redisConfig.GetString("address"), ","),
  52. Password: redisConfig.GetString("password"),
  53. DB: redisConfig.GetInt("database"),
  54. })
  55. }
  56. clog.Debug("redis address :" + redisConfig.GetString("address"))
  57. err := RDB.Set(context.Background(), "test", 0, 0).Err()
  58. if err != nil {
  59. clog.Errorf("redis client error: %v", err)
  60. }
  61. if p.App().NodeId() == "m-center" {
  62. SetIndex()
  63. }
  64. }