GO获取Nacos配置与监听

	Nacos官网地址:https://nacos.io/zh-cn/index.html
	
	Nacos下载地址:https://github.com/alibaba/nacos/releases
	百度网盘下载: https://pan.baidu.com/share/init?surl=186nmlqPGows9gUZKAx8Zw
	提取码 :rest

获取nacos配置

// 监听nacos配置
func getNacosConfig() (result int) {
	// 从控制台命名空间管理的"命名空间详情"中拷贝 End Point、命名空间 ID
	var endpoint = "127.0.0.1:8848/nacos"
	var namespaceId = ""
	// 推荐使用 RAM 用户的 accessKey、secretKey
	//var accessKey = "${accessKey}"
	//var secretKey = "${secretKey}"
	clientConfig := constant.ClientConfig{
		Endpoint:    endpoint,
		NamespaceId: namespaceId,
		//AccessKey:      accessKey,
		//SecretKey:      secretKey,
		TimeoutMs:      10 * 1000, //http请求超时时间,单位毫秒
		ListenInterval: 30 * 1000, //监听间隔时间,单位毫秒(仅在ConfigClient中有效)
		BeatInterval:   5 * 1000,  //心跳间隔时间,单位毫秒(仅在ServiceClient中有效)
	}

	// 至少一个
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      "127.0.0.1",
			ContextPath: "/nacos",
			Port:        8848,
		},
	}

	configClient, err := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})

	if err != nil {
		fmt.Println(err)
		return
	}

	var dataId = "sungyTest"
	var group = "DEFAULT_GROUP"

	// 获取配置
	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: dataId,
		Group:  group})

	fmt.Println("Get config:" + content)
	if len(content) == 0 {
		HLEFun.Errorln("getNacosConfigData - LoadErr , len is 0")
		result = 0
	}
	//监听nacos配置
	go ListenConfig()
	return
}

!!!觉得有用就点个赞!!!谢谢

监听nacos配置

// 监听nacos配置
func ListenConfig() {
	HLEFun.Messageln("开启nacos配置监听")
	// 从控制台命名空间管理的"命名空间详情"中拷贝 End Point、命名空间 ID
	var endpoint = "127.0.0.1:8848/nacos"
	clientConfig := constant.ClientConfig{
		Endpoint:    endpoint,
		NamespaceId: "",
		//AccessKey:      accessKey,
		//SecretKey:      secretKey,
		TimeoutMs:      10 * 1000, //http请求超时时间,单位毫秒
		ListenInterval: 30 * 1000, //监听间隔时间,单位毫秒(仅在ConfigClient中有效)
		BeatInterval:   5 * 1000,  //心跳间隔时间,单位毫秒(仅在ServiceClient中有效)
	}

	// 至少一个
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      "127.0.0.1",
			ContextPath: "/nacos",
			Port:        8848,
		},
	}

	configClient, err := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})

	if err != nil {
		fmt.Println(err)
		return
	}

	var dataId = "sungyTest"
	var group = "DEFAULT_GROUP"
	_ = configClient.ListenConfig(vo.ConfigParam{
		DataId: dataId,
		Group:  group,
		OnChange: func(namespace, group, dataId, data string) {
			fmt.Println("ListenConfig group:" + group + ", dataId:" + dataId + ", data:" + data)
			if len(data) == 0 {
				HLEFun.Errorln("getNacosConfigData - LoadErr , len is 0")
			}
		},
	})
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值