component.go 2.0 KB

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