config.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package apollo
  2. import (
  3. "fmt"
  4. "git.bvbej.com/bvbej/base-golang/pkg/env"
  5. "github.com/apolloconfig/agollo/v4"
  6. "github.com/apolloconfig/agollo/v4/component/log"
  7. apolloConfig "github.com/apolloconfig/agollo/v4/env/config"
  8. "github.com/apolloconfig/agollo/v4/storage"
  9. "github.com/spf13/viper"
  10. )
  11. type clientConfig struct {
  12. client agollo.Client
  13. ac *apolloConfig.AppConfig
  14. conf interface{}
  15. }
  16. func GetApolloConfig(appId, secret string, config interface{}) {
  17. var err error
  18. namespace := env.Active().Value() + ".yaml"
  19. c := new(clientConfig)
  20. c.conf = config
  21. c.ac = &apolloConfig.AppConfig{
  22. AppID: appId,
  23. Cluster: "dev",
  24. IP: "https://config.bvbej.com",
  25. NamespaceName: namespace,
  26. IsBackupConfig: true,
  27. Secret: secret,
  28. }
  29. agollo.SetLogger(&log.DefaultLogger{})
  30. c.client, err = agollo.StartWithConfig(func() (*apolloConfig.AppConfig, error) {
  31. return c.ac, nil
  32. })
  33. if err != nil {
  34. panic(fmt.Sprintf("get config error:[%s]", err))
  35. }
  36. c.client.AddChangeListener(c)
  37. err = c.serialization()
  38. if err != nil {
  39. panic(fmt.Sprintf("unmarshal config error:[%s]", err))
  40. }
  41. }
  42. func (c *clientConfig) serialization() error {
  43. viper.SetConfigType("yaml")
  44. c.client.GetConfigCache(c.ac.NamespaceName).Range(func(key, value interface{}) bool {
  45. viper.Set(key.(string), value)
  46. return true
  47. })
  48. return viper.Unmarshal(c.conf)
  49. }
  50. func (c *clientConfig) OnChange(*storage.ChangeEvent) {
  51. _ = c.serialization()
  52. }
  53. func (c *clientConfig) OnNewestChange(*storage.FullChangeEvent) {
  54. //
  55. }