1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- package apollo
- import (
- "git.bvbej.com/bvbej/base-golang/pkg/env"
- "git.bvbej.com/bvbej/base-golang/pkg/errors"
- "github.com/apolloconfig/agollo/v4"
- "github.com/apolloconfig/agollo/v4/component/log"
- apolloConfig "github.com/apolloconfig/agollo/v4/env/config"
- "github.com/apolloconfig/agollo/v4/storage"
- "github.com/spf13/viper"
- )
- type clientConfig struct {
- client agollo.Client
- ac *apolloConfig.AppConfig
- conf any
- onChange func(event *storage.ChangeEvent)
- onNewestChange func(*storage.FullChangeEvent)
- }
- type Option func(*clientConfig)
- func WithOnChangeEvent(event func(event *storage.ChangeEvent)) Option {
- return func(conf *clientConfig) {
- conf.onChange = event
- }
- }
- func WithOnNewestChangeEvent(event func(event *storage.FullChangeEvent)) Option {
- return func(conf *clientConfig) {
- conf.onNewestChange = event
- }
- }
- func GetApolloConfig(appId, secret string, config any, opt ...Option) error {
- var err error
- namespace := env.Active().Value() + ".yaml"
- c := new(clientConfig)
- c.conf = config
- c.ac = &apolloConfig.AppConfig{
- AppID: appId,
- Cluster: "dev",
- IP: "https://config.bvbej.com",
- NamespaceName: namespace,
- IsBackupConfig: true,
- Secret: secret,
- }
- for _, option := range opt {
- option(c)
- }
- agollo.SetLogger(&log.DefaultLogger{})
- c.client, err = agollo.StartWithConfig(func() (*apolloConfig.AppConfig, error) {
- return c.ac, nil
- })
- if err != nil {
- return errors.Errorf("get config error:[%s]", err)
- }
- c.client.AddChangeListener(c)
- err = c.serialization()
- if err != nil {
- return errors.Errorf("unmarshal config error:[%s]", err)
- }
- return nil
- }
- func (c *clientConfig) serialization() error {
- parser := viper.New()
- parser.SetConfigType("yaml")
- c.client.GetConfigCache(c.ac.NamespaceName).Range(func(key, value any) bool {
- parser.Set(key.(string), value)
- return true
- })
- return parser.Unmarshal(c.conf)
- }
- func (c *clientConfig) OnChange(event *storage.ChangeEvent) {
- _ = c.serialization()
- if c.onChange != nil {
- c.onChange(event)
- }
- }
- func (c *clientConfig) OnNewestChange(event *storage.FullChangeEvent) {
- if c.onNewestChange != nil {
- c.onNewestChange(event)
- }
- }
|