package main import ( "context" "fmt" "github.com/spf13/viper" _ "github.com/spf13/viper/remote" clientv3 "go.etcd.io/etcd/client/v3" "time" ) func main() { var ( client *clientv3.Client config clientv3.Config err error ) config = clientv3.Config{ // 这里的 Endpoints 是一个字符串数组切片,支持配合多个节点 Endpoints: []string{"106.54.33.152:2379"}, // DialTimeout 连接超时设置 DialTimeout: time.Duration(5) * time.Millisecond, } if client, err = clientv3.New(config); err != nil { return } // 设置 Viper 读取 etcd 配置 err = viper.AddRemoteProvider("etcd3", "106.54.33.152:2379", "/config/app") if err != nil { return } viper.SetConfigType("json") // etcd 中存储的配置类型 //读取配置 err = viper.ReadRemoteConfig() if err != nil { fmt.Printf("Error reading remote config: %v\n", err) return } // 打印初始配置 fmt.Println("Initial config:", viper.AllSettings()) // 设置监听 go ViperWatcher(client) time.Sleep(time.Second * 50) } func ViperWatcher(client *clientv3.Client) { ctx := context.Background() watch := client.Watch(ctx, "/config/app") for { select { case <-watch: err := viper.ReadRemoteConfig() if err != nil { fmt.Printf("Error reading remote config: %v\n", err) continue } fmt.Println("Updated config:", viper.AllSettings()) } } }