github.com/unionj-cloud/go-doudou@v1.3.8-0.20221011095552-0088008e5b31/framework/configmgr/apollo.go (about)

     1  package configmgr
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/apolloconfig/agollo/v4"
     6  	"github.com/apolloconfig/agollo/v4/env/config"
     7  	"github.com/apolloconfig/agollo/v4/storage"
     8  	"github.com/pkg/errors"
     9  	logger "github.com/unionj-cloud/go-doudou/toolkit/zlogger"
    10  	"os"
    11  	"strings"
    12  	"sync"
    13  )
    14  
    15  var onceApollo sync.Once
    16  var ApolloClient agollo.Client
    17  var StartWithConfig = agollo.StartWithConfig
    18  
    19  func InitialiseApolloConfig(appConfig *config.AppConfig) {
    20  	var err error
    21  	ApolloClient, err = StartWithConfig(func() (*config.AppConfig, error) {
    22  		return appConfig, nil
    23  	})
    24  	if err != nil {
    25  		panic(errors.Wrap(err, "[go-doudou] failed to initialise apollo client"))
    26  	}
    27  	logger.Info().Msg("[go-doudou] initialise apollo client successfully")
    28  }
    29  
    30  func LoadFromApollo(appConfig *config.AppConfig) {
    31  	onceApollo.Do(func() {
    32  		InitialiseApolloConfig(appConfig)
    33  	})
    34  	currentEnv := map[string]bool{}
    35  	namespaces := strings.Split(appConfig.NamespaceName, ",")
    36  	for _, item := range namespaces {
    37  		rawEnv := os.Environ()
    38  		for _, rawEnvLine := range rawEnv {
    39  			key := strings.Split(rawEnvLine, "=")[0]
    40  			currentEnv[key] = true
    41  		}
    42  		cache := ApolloClient.GetConfigCache(item)
    43  		cache.Range(func(key, value interface{}) bool {
    44  			logger.Debug().Msgf("[go-doudou] key: %s, value: %s\n", key, value)
    45  			upperK := strings.ToUpper(strings.ReplaceAll(key.(string), ".", "_"))
    46  			if !currentEnv[upperK] {
    47  				_ = os.Setenv(upperK, fmt.Sprint(value))
    48  			}
    49  			return true
    50  		})
    51  	}
    52  }
    53  
    54  type BaseApolloListener struct {
    55  	SkippedFirstEvent bool
    56  	Lock              sync.Mutex
    57  }
    58  
    59  func (c *BaseApolloListener) OnNewestChange(event *storage.FullChangeEvent) {
    60  }