github.com/fibonacci-chain/fbc@v0.0.0-20231124064014-c7636198c1e9/app/config/apollo.go (about) 1 package config 2 3 import ( 4 "fmt" 5 "strings" 6 7 "github.com/spf13/viper" 8 9 "github.com/apolloconfig/agollo/v4" 10 "github.com/apolloconfig/agollo/v4/env/config" 11 "github.com/apolloconfig/agollo/v4/storage" 12 ) 13 14 const FlagApollo = "config.apollo" 15 16 type ApolloClient struct { 17 Namespace string 18 *agollo.Client 19 fecConf *FecConfig 20 } 21 22 func NewApolloClient(fecConf *FecConfig) *ApolloClient { 23 // IP|AppID|NamespaceName 24 params := strings.Split(viper.GetString(FlagApollo), "|") 25 if len(params) != 3 { 26 panic("failed init apollo: invalid connection config") 27 } 28 29 c := &config.AppConfig{ 30 IP: params[0], 31 AppID: params[1], 32 NamespaceName: params[2], 33 Cluster: "default", 34 IsBackupConfig: false, 35 //Secret: "", 36 } 37 38 client, err := agollo.StartWithConfig(func() (*config.AppConfig, error) { 39 return c, nil 40 }) 41 if err != nil { 42 panic(fmt.Errorf("failed init apollo: %v", err)) 43 } 44 45 apc := &ApolloClient{ 46 params[2], 47 client, 48 fecConf, 49 } 50 client.AddChangeListener(&CustomChangeListener{fecConf}) 51 52 return apc 53 } 54 55 func (a *ApolloClient) LoadConfig() (loaded bool) { 56 cache := a.GetConfigCache(a.Namespace) 57 cache.Range(func(key, value interface{}) bool { 58 loaded = true 59 60 a.fecConf.update(key, value) 61 return true 62 }) 63 confLogger.Info(a.fecConf.format()) 64 return 65 } 66 67 type CustomChangeListener struct { 68 fecConf *FecConfig 69 } 70 71 func (c *CustomChangeListener) OnChange(changeEvent *storage.ChangeEvent) { 72 for key, value := range changeEvent.Changes { 73 if value.ChangeType != storage.DELETED { 74 c.fecConf.update(key, value.NewValue) 75 } 76 } 77 confLogger.Info(c.fecConf.format()) 78 } 79 80 func (c *CustomChangeListener) OnNewestChange(event *storage.FullChangeEvent) { 81 return 82 }