titansSdk.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package titansSdk
  2. import (
  3. "context"
  4. "go-common/app/service/live/resource/api/grpc/v1"
  5. "go-common/library/ecode"
  6. "go-common/library/log"
  7. "go-common/library/net/rpc/warden"
  8. "sync/atomic"
  9. "time"
  10. )
  11. // titansConfigSdk 初始化时 单实例对象
  12. var titansConfigSdk = &titansSdk{}
  13. // Config 服务可配置项
  14. type Config struct {
  15. // 服务的tree_id
  16. TreeId int64
  17. // 缓存的更新间隔,单位为s,不配置则为5s
  18. Expire int64
  19. }
  20. // titansSdk sdk
  21. type titansSdk struct {
  22. client v1.TitansClient
  23. cache atomic.Value
  24. }
  25. // Init 业务初始化sdk接口
  26. func Init(titansConfig *Config) {
  27. conf := &warden.ClientConfig{}
  28. client := warden.NewClient(conf)
  29. conn, err := client.Dial(context.Background(), "discovery://default/"+v1.AppID)
  30. if err != nil {
  31. panic("依赖TitansConfig, 但是Titans的Client没有创建成功!")
  32. }
  33. if titansConfig.TreeId == 0 {
  34. panic("依赖了TitansConfig, 但是titansConfig的treeId配置为空!")
  35. }
  36. titansConfigSdk = &titansSdk{}
  37. titansConfigSdk.client = v1.NewTitansClient(conn)
  38. titansConfigSdk.cache.Store(make(map[string]string))
  39. load(titansConfigSdk, titansConfig.TreeId)
  40. go update(titansConfigSdk, titansConfig.TreeId, titansConfig.Expire)
  41. }
  42. // update 定时更新
  43. func update(sdk *titansSdk, treeId int64, expire int64) {
  44. if expire < 1 {
  45. expire = 5
  46. }
  47. for {
  48. load(sdk, treeId)
  49. time.Sleep(time.Duration(expire) * time.Second)
  50. }
  51. }
  52. // load grpc接口
  53. func load(sdk *titansSdk, treeId int64) {
  54. for {
  55. resp, err := sdk.client.GetByTreeId(context.Background(), &v1.TreeIdReq{TreeId: treeId})
  56. if err != nil {
  57. log.Error("[SyncTitansConfig][call resource][error], err:%+v", err)
  58. } else {
  59. sdk.cache.Store(resp.List)
  60. break
  61. }
  62. time.Sleep(1 * time.Second)
  63. }
  64. }
  65. // Get 获取配置接口
  66. func Get(keyword string) (res string, err error) {
  67. res = ""
  68. cache, ok := titansConfigSdk.cache.Load().(map[string]string)
  69. if !ok {
  70. log.Error("[GetTitansConfig][cache content exception][error] content assert failed")
  71. err = ecode.GetConfAdminErr
  72. return
  73. }
  74. res, ok = cache[keyword]
  75. if !ok || res == "" {
  76. log.Error("[GetTitansConfig][cache content empty][Warn], keyword:%s, cache:%v", keyword, cache)
  77. err = ecode.GetConfAdminErr
  78. return
  79. }
  80. return
  81. }