config.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package apollo
  2. import (
  3. "git.bvbej.com/bvbej/base-golang/pkg/env"
  4. "git.bvbej.com/bvbej/base-golang/pkg/errors"
  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 any
  15. change func(event *storage.ChangeEvent)
  16. }
  17. func GetApolloConfig(appId, secret string, config any, change func(event *storage.ChangeEvent)) error {
  18. var err error
  19. namespace := env.Active().Value() + ".yaml"
  20. c := new(clientConfig)
  21. c.conf = config
  22. c.change = change
  23. c.ac = &apolloConfig.AppConfig{
  24. AppID: appId,
  25. Cluster: "dev",
  26. IP: "https://config.bvbej.com",
  27. NamespaceName: namespace,
  28. IsBackupConfig: true,
  29. Secret: secret,
  30. }
  31. agollo.SetLogger(&log.DefaultLogger{})
  32. c.client, err = agollo.StartWithConfig(func() (*apolloConfig.AppConfig, error) {
  33. return c.ac, nil
  34. })
  35. if err != nil {
  36. return errors.Errorf("get config error:[%s]", err)
  37. }
  38. c.client.AddChangeListener(c)
  39. err = c.serialization()
  40. if err != nil {
  41. return errors.Errorf("unmarshal config error:[%s]", err)
  42. }
  43. return nil
  44. }
  45. func (c *clientConfig) serialization() error {
  46. parser := viper.New()
  47. parser.SetConfigType("yaml")
  48. c.client.GetConfigCache(c.ac.NamespaceName).Range(func(key, value any) bool {
  49. parser.Set(key.(string), value)
  50. return true
  51. })
  52. return parser.Unmarshal(c.conf)
  53. }
  54. func (c *clientConfig) OnChange(event *storage.ChangeEvent) {
  55. _ = c.serialization()
  56. c.change(event)
  57. }
  58. func (c *clientConfig) OnNewestChange(*storage.FullChangeEvent) {
  59. //
  60. }