nacos-viper-remote/config_remote_provider.go

65 lines
1.6 KiB
Go
Raw Permalink Normal View History

2021-05-12 13:34:53 +08:00
package nacos_viper_remote
import (
2021-07-29 19:30:03 +08:00
"bytes"
2021-05-12 13:34:53 +08:00
"fmt"
"github.com/spf13/viper"
)
type ViperRemoteProvider struct {
2021-05-12 13:56:58 +08:00
configType string
configSet string
2021-05-12 13:34:53 +08:00
}
2021-05-12 13:56:58 +08:00
func NewRemoteProvider(configType string) *ViperRemoteProvider {
2021-05-12 13:34:53 +08:00
return &ViperRemoteProvider{
2021-05-12 13:56:58 +08:00
configType: configType,
configSet: "yoyogo.cloud.discovery.metadata"}
2021-05-12 13:34:53 +08:00
}
2021-07-29 19:30:03 +08:00
func (provider *ViperRemoteProvider) GetProvider(runtimeViper *viper.Viper) *viper.Viper {
2021-05-12 13:34:53 +08:00
var option *Option
2021-07-29 19:30:03 +08:00
err := runtimeViper.Sub(provider.configSet).Unmarshal(&option)
2021-05-12 13:34:53 +08:00
if err != nil {
panic(err)
return nil
}
SetOptions(option)
remote_viper := viper.New()
err = remote_viper.AddRemoteProvider("nacos", "localhost", "")
2021-05-12 13:56:58 +08:00
if provider.configType == "" {
provider.configType = "yaml"
}
remote_viper.SetConfigType(provider.configType)
2021-05-12 13:34:53 +08:00
err = remote_viper.ReadRemoteConfig()
if err == nil {
2021-07-29 19:30:03 +08:00
//err = remote_viper.WatchRemoteConfigOnChannel()
2021-05-12 13:34:53 +08:00
if err == nil {
2021-07-30 12:26:44 +08:00
fmt.Println("config center ..........")
fmt.Println("used remote viper by Nacos")
fmt.Printf("Nacos config: namespace: %s , group: %s", option.NamespaceId, option.GroupName)
2021-05-12 13:34:53 +08:00
return remote_viper
}
} else {
panic(err)
}
2021-07-29 19:30:03 +08:00
return runtimeViper
}
func (provider *ViperRemoteProvider) WatchRemoteConfigOnChannel(remoteViper *viper.Viper) <-chan bool {
updater := make(chan bool)
respChan, _ := viper.RemoteConfig.WatchChannel(DefaultRemoteProvider())
go func(rc <-chan *viper.RemoteResponse) {
for {
b := <-rc
reader := bytes.NewReader(b.Value)
_ = remoteViper.ReadConfig(reader)
// configuration on changed
updater <- true
}
}(respChan)
return updater
2021-05-12 13:34:53 +08:00
}