main.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "strings"
  6. "github.com/nacos-group/nacos-sdk-go/clients"
  7. "github.com/nacos-group/nacos-sdk-go/common/constant"
  8. "github.com/nacos-group/nacos-sdk-go/vo"
  9. "github.com/spf13/viper"
  10. )
  11. var (
  12. defaultConfig *viper.Viper
  13. nacosIp string
  14. nacosPort uint64
  15. nacosDataId string
  16. nacosGroup string
  17. )
  18. func initConfig() *viper.Viper {
  19. nacosIp = "127.0.0.1"
  20. nacosPort = 8848
  21. nacosDataId = "dev001"
  22. nacosGroup = "DEFAULT_GROUP"
  23. defaultConfig = viper.New()
  24. defaultConfig.SetConfigType("toml")
  25. //配置模型
  26. serverConfigs := []constant.ServerConfig{
  27. {
  28. IpAddr: nacosIp,
  29. Port: nacosPort,
  30. },
  31. }
  32. //客户端
  33. nacosClient, err := clients.NewConfigClient(
  34. vo.NacosClientParam{
  35. ClientConfig: &constant.ClientConfig{TimeoutMs: 5000,NamespaceId:"36a76206-1dec-4fb7-aa7f-dc49314e7963",LogLevel:"debug"},
  36. //ClientConfig: &constant.ClientConfig{TimeoutMs: 5000},
  37. ServerConfigs: serverConfigs,
  38. },
  39. )
  40. if err != nil {
  41. log.Fatal("nacos初始化错误:", err)
  42. }
  43. content, err := nacosClient.GetConfig(vo.ConfigParam{DataId: nacosDataId, Group: nacosGroup})
  44. if err != nil {
  45. log.Fatalln("nacos读取配置错误:" + content)
  46. }
  47. err = defaultConfig.ReadConfig(strings.NewReader(content))
  48. if err != nil {
  49. log.Fatalln("Viper解析配置失败:", err)
  50. }
  51. //go func() {
  52. // time.Sleep(time.Second * 10)
  53. // err = nacosClient.ListenConfig(vo.ConfigParam{
  54. // DataId: nacosDataId,
  55. // Group: nacosGroup,
  56. // OnChange: func(namespace, group, dataId, data string) {
  57. // fmt.Println("config changed group:" + group + ", dataId:" + dataId + ", content:" + data)
  58. // err = defaultConfig.ReadConfig(strings.NewReader(data))
  59. // if err != nil {
  60. // log.Fatalln("Viper解析配置失败:", err)
  61. // }
  62. // },
  63. // })
  64. //}()
  65. return defaultConfig
  66. }
  67. func GetConfig() *viper.Viper {
  68. if defaultConfig == nil {
  69. defaultConfig = initConfig()
  70. }
  71. return defaultConfig
  72. }
  73. func main() {
  74. //for {
  75. host := GetConfig().GetString("server.port")
  76. fmt.Println("consul===", host)
  77. //time.Sleep(time.Second * 10)
  78. //}
  79. }