config.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package apollo
  2. import (
  3. "git.bvbej.com/bvbej/base-golang/pkg/env"
  4. "github.com/apolloconfig/agollo/v4"
  5. "github.com/apolloconfig/agollo/v4/component/log"
  6. apolloConfig "github.com/apolloconfig/agollo/v4/env/config"
  7. "github.com/apolloconfig/agollo/v4/storage"
  8. "github.com/pkg/errors"
  9. "github.com/spf13/viper"
  10. )
  11. type clientConfig struct {
  12. client agollo.Client
  13. ac *apolloConfig.AppConfig
  14. conf any
  15. }
  16. func GetApolloConfig(appId, secret string, config any) error {
  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. return errors.Errorf("get config error:[%s]", err)
  35. }
  36. c.client.AddChangeListener(c)
  37. err = c.serialization()
  38. if err != nil {
  39. return errors.Errorf("unmarshal config error:[%s]", err)
  40. }
  41. return nil
  42. }
  43. func (c *clientConfig) serialization() error {
  44. parser := viper.New()
  45. parser.SetConfigType("yaml")
  46. c.client.GetConfigCache(c.ac.NamespaceName).Range(func(key, value any) bool {
  47. parser.Set(key.(string), value)
  48. return true
  49. })
  50. return parser.Unmarshal(c.conf)
  51. }
  52. func (c *clientConfig) OnChange(*storage.ChangeEvent) {
  53. _ = c.serialization()
  54. }
  55. func (c *clientConfig) OnNewestChange(*storage.FullChangeEvent) {
  56. //
  57. }