source_redis.go 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. package mhayaDataConfig
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/go-redis/redis/v8"
  6. cerr "github.com/mhaya/error"
  7. clog "github.com/mhaya/logger"
  8. cprofile "github.com/mhaya/profile"
  9. )
  10. type (
  11. // SourceRedis redis方式获取数据配置
  12. //
  13. // 从profile-x.json中获取data_config的属性配置,
  14. // 如果"data_source"的值为"redis",则启用redis方式读取数据配置.
  15. // 通过redis的订阅机制来触发哪个配置有变更,则进行重新加载处理.
  16. // 程序启动后,会订阅“subscribeKey”,当有变更时,则执行加载.
  17. SourceRedis struct {
  18. redisConfig
  19. changeFn ConfigChangeFn
  20. close chan bool
  21. rdb *redis.Client
  22. }
  23. redisConfig struct {
  24. Address string `json:"address"` // redis地址
  25. Password string `json:"password"` // 密码
  26. DB int `json:"database"` // database index
  27. PrefixKey string `json:"prefix_key"` // 前缀
  28. SubscribeKey string `json:"subscribe_key"` // 订阅key
  29. }
  30. )
  31. func (r *SourceRedis) Name() string {
  32. return "redis"
  33. }
  34. func (r *SourceRedis) Init(_ IDataConfig) {
  35. //read data_config->file node
  36. dataConfig := cprofile.GetConfig("data_config").GetConfig(r.Name())
  37. if dataConfig.Unmarshal(&r.redisConfig) != nil {
  38. clog.Warnf("[data_config]->[%s] node in `%s` file not found.", r.Name(), cprofile.Name())
  39. return
  40. }
  41. r.newRedis()
  42. r.close = make(chan bool)
  43. go r.newSubscribe()
  44. }
  45. func (r *SourceRedis) newRedis() {
  46. r.rdb = redis.NewClient(&redis.Options{
  47. Addr: r.Address,
  48. Password: r.Password,
  49. DB: r.DB,
  50. OnConnect: func(ctx context.Context, cn *redis.Conn) error {
  51. clog.Infof("data config for redis connected")
  52. return nil
  53. },
  54. })
  55. }
  56. func (r *SourceRedis) newSubscribe() {
  57. if r.SubscribeKey == "" {
  58. panic("subscribe key is empty.")
  59. }
  60. sub := r.rdb.Subscribe(context.Background(), r.SubscribeKey)
  61. defer func(sub *redis.PubSub) {
  62. err := sub.Close()
  63. if err != nil {
  64. clog.Warn(err)
  65. }
  66. }(sub)
  67. for {
  68. select {
  69. case <-r.close:
  70. return
  71. case ch := <-sub.Channel():
  72. if ch.Payload == "" {
  73. continue
  74. }
  75. clog.Infof("[name = %s] trigger file change.", ch.Payload)
  76. data, err := r.ReadBytes(ch.Payload)
  77. if err != nil {
  78. clog.Warnf("[name = %s] read data error = %s", ch.Payload, err)
  79. continue
  80. }
  81. if r.changeFn != nil {
  82. r.changeFn(ch.Payload, data)
  83. }
  84. }
  85. }
  86. }
  87. func (r *SourceRedis) ReadBytes(configName string) ([]byte, error) {
  88. if configName == "" {
  89. return nil, cerr.Error("configName is empty.")
  90. }
  91. key := fmt.Sprintf("%s:%s", r.PrefixKey, configName)
  92. return r.rdb.Get(context.Background(), key).Bytes()
  93. }
  94. func (r *SourceRedis) OnChange(fn ConfigChangeFn) {
  95. r.changeFn = fn
  96. }
  97. func (r *SourceRedis) Stop() {
  98. clog.Infof("close redis client [address = %s]", r.Address)
  99. r.close <- true
  100. if r.rdb != nil {
  101. err := r.rdb.Close()
  102. if err != nil {
  103. clog.Error(err)
  104. }
  105. }
  106. }