main.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/spf13/viper"
  6. _ "github.com/spf13/viper/remote"
  7. clientv3 "go.etcd.io/etcd/client/v3"
  8. "time"
  9. )
  10. func main() {
  11. var (
  12. client *clientv3.Client
  13. config clientv3.Config
  14. err error
  15. )
  16. config = clientv3.Config{
  17. // 这里的 Endpoints 是一个字符串数组切片,支持配合多个节点
  18. Endpoints: []string{"106.54.33.152:2379"},
  19. // DialTimeout 连接超时设置
  20. DialTimeout: time.Duration(5) * time.Millisecond,
  21. }
  22. if client, err = clientv3.New(config); err != nil {
  23. return
  24. }
  25. // 设置 Viper 读取 etcd 配置
  26. err = viper.AddRemoteProvider("etcd3", "106.54.33.152:2379", "/config/app")
  27. if err != nil {
  28. return
  29. }
  30. viper.SetConfigType("json") // etcd 中存储的配置类型
  31. //读取配置
  32. err = viper.ReadRemoteConfig()
  33. if err != nil {
  34. fmt.Printf("Error reading remote config: %v\n", err)
  35. return
  36. }
  37. // 打印初始配置
  38. fmt.Println("Initial config:", viper.AllSettings())
  39. // 设置监听
  40. go ViperWatcher(client)
  41. time.Sleep(time.Second * 50)
  42. }
  43. func ViperWatcher(client *clientv3.Client) {
  44. ctx := context.Background()
  45. watch := client.Watch(ctx, "/config/app")
  46. for {
  47. select {
  48. case <-watch:
  49. err := viper.ReadRemoteConfig()
  50. if err != nil {
  51. fmt.Printf("Error reading remote config: %v\n", err)
  52. continue
  53. }
  54. fmt.Println("Updated config:", viper.AllSettings())
  55. }
  56. }
  57. }