config.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. onChange func(event *storage.ChangeEvent)
  16. onNewestChange func(*storage.FullChangeEvent)
  17. }
  18. type Option func(*clientConfig)
  19. func WithOnChangeEvent(event func(event *storage.ChangeEvent)) Option {
  20. return func(conf *clientConfig) {
  21. conf.onChange = event
  22. }
  23. }
  24. func WithOnNewestChangeEvent(event func(event *storage.FullChangeEvent)) Option {
  25. return func(conf *clientConfig) {
  26. conf.onNewestChange = event
  27. }
  28. }
  29. func GetApolloConfig(appId, secret string, config any, opt ...Option) error {
  30. var err error
  31. namespace := env.Active().Value() + ".yaml"
  32. c := new(clientConfig)
  33. c.conf = config
  34. c.ac = &apolloConfig.AppConfig{
  35. AppID: appId,
  36. Cluster: "dev",
  37. IP: "https://config.bvbej.com",
  38. NamespaceName: namespace,
  39. IsBackupConfig: true,
  40. Secret: secret,
  41. }
  42. for _, option := range opt {
  43. option(c)
  44. }
  45. agollo.SetLogger(&log.DefaultLogger{})
  46. c.client, err = agollo.StartWithConfig(func() (*apolloConfig.AppConfig, error) {
  47. return c.ac, nil
  48. })
  49. if err != nil {
  50. return errors.Errorf("get config error:[%s]", err)
  51. }
  52. c.client.AddChangeListener(c)
  53. err = c.serialization()
  54. if err != nil {
  55. return errors.Errorf("unmarshal config error:[%s]", err)
  56. }
  57. return nil
  58. }
  59. func (c *clientConfig) serialization() error {
  60. parser := viper.New()
  61. parser.SetConfigType("yaml")
  62. c.client.GetConfigCache(c.ac.NamespaceName).Range(func(key, value any) bool {
  63. parser.Set(key.(string), value)
  64. return true
  65. })
  66. return parser.Unmarshal(c.conf)
  67. }
  68. func (c *clientConfig) OnChange(event *storage.ChangeEvent) {
  69. _ = c.serialization()
  70. if c.onChange != nil {
  71. c.onChange(event)
  72. }
  73. }
  74. func (c *clientConfig) OnNewestChange(event *storage.FullChangeEvent) {
  75. if c.onNewestChange != nil {
  76. c.onNewestChange(event)
  77. }
  78. }