config.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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 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: false,
  40. Secret: secret,
  41. MustStart: true,
  42. }
  43. for _, option := range opt {
  44. option(c)
  45. }
  46. agollo.SetLogger(&log.DefaultLogger{})
  47. c.client, err = agollo.StartWithConfig(func() (*apolloConfig.AppConfig, error) {
  48. return c.ac, nil
  49. })
  50. if err != nil {
  51. return fmt.Errorf("get config error:[%s]", err)
  52. }
  53. c.client.AddChangeListener(c)
  54. err = c.serialization()
  55. if err != nil {
  56. return fmt.Errorf("unmarshal config error:[%s]", err)
  57. }
  58. return nil
  59. }
  60. func (c *clientConfig) serialization() error {
  61. parser := viper.New()
  62. parser.SetConfigType("yaml")
  63. c.client.GetConfigCache(c.ac.NamespaceName).Range(func(key, value any) bool {
  64. parser.Set(key.(string), value)
  65. return true
  66. })
  67. return parser.Unmarshal(c.conf)
  68. }
  69. func (c *clientConfig) OnChange(event *storage.ChangeEvent) {
  70. _ = c.serialization()
  71. if c.onChange != nil {
  72. c.onChange(event)
  73. }
  74. }
  75. func (c *clientConfig) OnNewestChange(event *storage.FullChangeEvent) {
  76. if c.onNewestChange != nil {
  77. c.onNewestChange(event)
  78. }
  79. }