首页 > 其他分享 >go集成nacos

go集成nacos

时间:2022-11-12 14:00:41浏览次数:64  
标签:集成 string err nacos json go mapstructure port

一. nacos介绍及安装

1. 官网

https://nacos.io/zh-cn/docs/quick-start.html

 

二.集成go

1.官网地址

https://github.com/nacos-group/nacos-sdk-go

2. 使用 

package main

import (
	"OldPackageTest/nacos_test/config"
	"encoding/json"
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"time"
)

func main() {
	sc := []constant.ServerConfig{
		{
			IpAddr: "127.0.0.1",
			Port:   8848,
		},
	}

	cc := constant.ClientConfig{
		NamespaceId:         "92e0d4cc-d03c-4d66-8530-dd598501ad29", // 如果需要支持多namespace,我们可以场景多个client,它们有不同的NamespaceId
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "tmp/nacos/log",
		CacheDir:            "tmp/nacos/cache",
		RotateTime:          "1h",
		MaxAge:              3,
		LogLevel:            "debug",
	}

	configClient, err := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": sc,
		"clientConfig":  cc,
	})
	if err != nil {
		panic(err)
	}

	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: "user-web.yaml",
		Group:  "dev"})

	if err != nil {
		panic(err)
	}
	//读取配置
	fmt.Println(content)

	//fmt.Println(content) //字符串 - yaml
	serverConfig := config.ServerConfig{}
	//想要将一个json字符串转换成struct,需要去设置这个struct的tag
	json.Unmarshal([]byte(content), &serverConfig)
	fmt.Println(serverConfig)

	//监听配置文件的变化
	err = configClient.ListenConfig(vo.ConfigParam{
		DataId: "user-web.yaml",
		Group:  "dev",
		OnChange: func(namespace, group, dataId, data string) {
			fmt.Println("配置文件变化")
			fmt.Println("group:" + group + ", dataId:" + dataId + ", data:" + data)
		},
	})
	time.Sleep(3000 * time.Second)

}
 

三.service集成nacos

1. 如何将yaml映射成struct结构体

在上述测试中可以看出,读取的时候返回的数据类型为字符串类型,那如何映射成go 的结构体呢

解决方案: go语言本身支持将json的字符串反射成结构体

在线转换测试地址:https://json2yaml.com/convert-yaml-to-json

 

在nacos上创建json的数据格式相关的配置文件

{
  "name": "user-web",
  "port": 8021,
  "user_srv": {
    "host": "127.0.0.1",
    "port": 50051,
    "name": "user-srv"
  },
  "jwt": {
    "key": "fx4Xg7YPud$jji$y3XCCsReQcvMuZim^"
  },
  "sms": {
    "key": "",
    "secrect": "",
    "expire": 30
  },
  "redis": {
    "host": "127.0.0.1",
    "port": 6379
  },
  "consul": {
    "host": "127.0.0.1",
    "port": 8500
  }
}

详细配置信息如下

 

相关代码

package main

import (
	"OldPackageTest/nacos_test/config"
	"encoding/json"
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
)

func main() {
	sc := []constant.ServerConfig{
		{
			IpAddr: "127.0.0.1",
			Port:   8848,
		},
	}

	cc := constant.ClientConfig{
		NamespaceId:         "92e0d4cc-d03c-4d66-8530-dd598501ad29", // 如果需要支持多namespace,我们可以场景多个client,它们有不同的NamespaceId
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "tmp/nacos/log",
		CacheDir:            "tmp/nacos/cache",
		RotateTime:          "1h",
		MaxAge:              3,
		LogLevel:            "debug",
	}

	configClient, err := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": sc,
		"clientConfig":  cc,
	})
	if err != nil {
		panic(err)
	}

	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: "user-web.json",
		Group:  "dev"})

	if err != nil {
		panic(err)
	}
	//读取配置
	//fmt.Println(content)

	//fmt.Println(content) //字符串 - yaml
	serverConfig := config.ServerConfig{}
	//想要将一个json字符串转换成struct,需要去设置这个struct的tag
	json.Unmarshal([]byte(content), &serverConfig)
	fmt.Println(serverConfig)

	//监听配置文件的变化
	//err = configClient.ListenConfig(vo.ConfigParam{
	//	DataId: "user-web.json",
	//	Group:  "dev",
	//	OnChange: func(namespace, group, dataId, data string) {
	//		fmt.Println("配置文件变化")
	//		fmt.Println("group:" + group + ", dataId:" + dataId + ", data:" + data)
	//	},
	//})
	//time.Sleep(3000 * time.Second)

}

 config配置文件中添加

json:"xxx"
package config

type UserSrvConfig struct {
	Host string `mapstructure:"host" json:"host"`
	Port int    `mapstructure:"port" json:"port"`
	Name string `mapstructure:"name" json:"name"`
}

type ServerConfig struct {
	Name         string        `mapstructure:"name" json:"name"`
	Port         int           `mapstructure:"port" json:"port"`
	UserSrvInfo  UserSrvConfig `mapstructure:"user_srv" json:"user_srv"`
	JWTInfo      JWTConfig     `mapstructure:"jwt" json:"jwt"`
	AliSmsConfig AliSmsConfig  `mapstructure:"sms" json:"nsmsame"`
	RedisConfig  RedisConfig   `mapstructure:"redis" json:"redis"`
	ConsulInfo   ConsulConfig  `mapstructure:"consul" json:"consul"`
}

type JWTConfig struct {
	SigningKey string `mapstructure:"key" json:"key"`
}

type AliSmsConfig struct {
	ApiKey     string `mapstructure:"key" json:"key"`
	ApiSecrect string `mapstructure:"secrect" json:"secrect"`
}

type RedisConfig struct {
	Host   string `mapstructure:"host" json:"host"`
	Port   int    `mapstructure:"port" json:"port"`
	Expire int    `mapstructure:"expire" json:"expire"`
}

type ConsulConfig struct {
	Host string `mapstructure:"host" json:"host"`
	Port int    `mapstructure:"port" json:"port"`
}

type Nacos struct {
	Host      string `mapstructure:"host" json:"host"`
	Port      uint64 `mapstructure:"port" json:"port"`
	User      string `mapstructure:"user" json:"user"`
	Password  string `mapstructure:"password" json:"password"`
	NameSpace string `mapstructure:"namespace" json:"namespace"`
	DataId    string `mapstructure:"dataid" json:"dataid"`
	Group     string `mapstructure:"group" json:"group"`
}

  

2. 在项目中使用

1. 更改config的配置信息

user-web/config/config.go文件添加json:"xxx"以供json解析使用

package config

type UserSrvConfig struct {
	Host string `mapstructure:"host" json:"host"`
	Port int    `mapstructure:"port" json:"port"`
	Name string `mapstructure:"name" json:"name"`
}

type ServerConfig struct {
	Name         string        `mapstructure:"name" json:"name"`
	Port         int           `mapstructure:"port" json:"port"`
	UserSrvInfo  UserSrvConfig `mapstructure:"user_srv" json:"user_srv"`
	JWTInfo      JWTConfig     `mapstructure:"jwt" json:"jwt"`
	AliSmsConfig AliSmsConfig  `mapstructure:"sms" json:"nsmsame"`
	RedisConfig  RedisConfig   `mapstructure:"redis" json:"redis"`
	ConsulInfo   ConsulConfig  `mapstructure:"consul" json:"consul"`
}

type JWTConfig struct {
	SigningKey string `mapstructure:"key" json:"key"`
}

type AliSmsConfig struct {
	ApiKey     string `mapstructure:"key" json:"key"`
	ApiSecrect string `mapstructure:"secrect" json:"secrect"`
}

type RedisConfig struct {
	Host   string `mapstructure:"host" json:"host"`
	Port   int    `mapstructure:"port" json:"port"`
	Expire int    `mapstructure:"expire" json:"expire"`
}

type ConsulConfig struct {
	Host string `mapstructure:"host" json:"host"`
	Port int    `mapstructure:"port" json:"port"`
}

2.增加nacos的结构体配置

type Nacos struct {
	Host      string `mapstructure:"host" json:"host"`
	Port      uint64 `mapstructure:"port" json:"port"`
	User      string `mapstructure:"user" json:"user"`
	Password  string `mapstructure:"password" json:"password"`
	NameSpace string `mapstructure:"namespace" json:"namespace"`
	DataId    string `mapstructure:"dataid" json:"dataid"`
	Group     string `mapstructure:"group" json:"group"`
}
 

3.增加yaml的相关nacos的配置

在config-debug.yaml中增加nacos的相关配置信息

#nacos:
host: '127.0.0.1'
port: 8848
namespace: '92e0d4cc-d03c-4d66-8530-dd598501ad29'
user: 'nacos'
password: 'nacos'
dataid: 'user-web.json'
group: 'dev'

 以上就完成了配置的配置,接下来就是对配置的读取

 

4.配置读取

在initialize/config.go中,更新InitConfig函数,将原来的读取本地的配置文件,更改为读取nacos的配置,并把配置映射给结构体及全局&global.ServerConfig变量

package initialize

import (
	"encoding/json"
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"mxshop-api/user-web/global"
)

func GetEnvInfo(env string) bool {
	viper.AutomaticEnv()
	return viper.GetBool(env)
	//刚才设置的环境变量 想要生效 我们必须得重启goland
}

//func InitConfig() {
//读取本地配置文件时候的配置
//	fmt.Println(GetEnvInfo("MXSHOP_DEBUG"))
//	//配置环境变量
//	debug := GetEnvInfo("MXSHOP_DEBUG")
//	configFilePrefix := "config"
//	configFileName := fmt.Sprintf("user-web/%s-pro.yaml", configFilePrefix)
//	if debug {
//		configFileName = fmt.Sprintf("user-web/%s-debug.yaml", configFilePrefix)
//	}
//
//	v := viper.New()
//	//文件的路径如何设置
//	v.SetConfigFile(configFileName)
//	if err := v.ReadInConfig(); err != nil {
//		panic(err)
//	}
//	if err := v.Unmarshal(global.ServerConfig); err != nil {
//		panic(err)
//	}
//	zap.S().Infof("配置文件:&v", configFileName)
//
//	zap.S().Infof("配置信息:&v", global.ServerConfig)
//
//	//viper的功能 - 动态监控变化
//	v.WatchConfig()
//	v.OnConfigChange(func(e fsnotify.Event) {
//		zap.S().Infof("配置产生变化:&v", e.Name)
//
//		fmt.Println("config file channed: ", e.Name)
//		_ = v.ReadInConfig()
//		_ = v.Unmarshal(&global.ServerConfig)
//		zap.S().Infof("配置信息:&v", global.ServerConfig)
//	})
//}

func InitConfig() {
	//读取nacos的配置
	fmt.Println(GetEnvInfo("MXSHOP_DEBUG"))
	//配置环境变量
	debug := GetEnvInfo("MXSHOP_DEBUG")
	configFilePrefix := "config"
	configFileName := fmt.Sprintf("user-web/%s-pro.yaml", configFilePrefix)
	if debug {
		configFileName = fmt.Sprintf("user-web/%s-debug.yaml", configFilePrefix)
	}

	v := viper.New()
	//文件的路径如何设置
	v.SetConfigFile(configFileName)
	if err := v.ReadInConfig(); err != nil {
		panic(err)
	}
	if err := v.Unmarshal(global.NacosConfig); err != nil {
		panic(err)
	}
	zap.S().Infof("配置信息:&v", global.NacosConfig)

	//	从nacos中读取配置信息
	sc := []constant.ServerConfig{
		{
			IpAddr: global.NacosConfig.Host,
			Port:   global.NacosConfig.Port,
		},
	}

	cc := constant.ClientConfig{
		NamespaceId:         global.NacosConfig.NameSpace, // 如果需要支持多namespace,我们可以场景多个client,它们有不同的NamespaceId
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "tmp/nacos/log",
		CacheDir:            "tmp/nacos/cache",
		LogLevel:            "debug",
	}

	configClient, err := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": sc,
		"clientConfig":  cc,
	})
	if err != nil {
		panic(err)
	}

	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: global.NacosConfig.DataId,
		Group:  global.NacosConfig.Group})

	if err != nil {
		panic(err)
	}
	//读取配置
	//fmt.Println(content)

	//fmt.Println(content) //字符串 - yaml
	//想要将一个json字符串转换成struct,需要去设置这个struct的tag
	err = json.Unmarshal([]byte(content), &global.ServerConfig)
	if err != nil {
		zap.S().Fatalf("服务nacos配置失败:%s", err.Error())
	}
	fmt.Println(&global.ServerConfig)
}

  

 

 

 

 

 

标签:集成,string,err,nacos,json,go,mapstructure,port
From: https://www.cnblogs.com/wlike/p/16883611.html

相关文章

  • 使用Argocd部署应用
    部署helloworld[root@master07-argocd-basics]#kubectlapply-f01-application-helloworld.yamlapplication.argoproj.io/spring-boot-helloworldcreated[root@ma......
  • Go进阶36:Goland远程开发调试
    Go进阶36:Goland远程开发调试Go&Rust......
  • 这些不知道,别说你熟悉 Nacos,深度源码解析!
    SpringCloud应用启动拉去配置我们之前写过一篇文章,介绍了一些Spring提供的扩展机制。其中说到了ApplicationContextInitializer,该扩展是在上下文准备阶段(prepareContext......
  • Mongodb中的PSA转换为PSS架构
    PSA架构的问题众所周知,PSA架构中如果Secondary发生故障会带来一系列的问题,包括Majority写入无法完成造成主库内存压力的增加重启主库需要更多的时间特殊情况下会导致数据的......
  • Go 语言项目源码解析:定时任务库 cron
    环境准备首先我们将源码克隆(Fork)为自己的个人仓库,只需要在GitHub项目主页点击Fork按钮,然后输入项目名称点击确认即可。克隆完毕后,可以下载到本地,或者直接在科隆后的Git......
  • Idea/goland go debug : version of delve is too old for this version of go.
    terminal:gogetgithub.com/go-delve/delve/cmd/dlv1、拿到最新的dlv.exe。位置在gopath的lib目录下的bin目录。2、help>EditCustomProperties:创建一个properties......
  • 关于Go 包管理
      0、包管理的历史Golang的包管理一直被大众所诟病的一个点,但是我们可以看到现在确实是在往好的方向进行发展。下面是官方的包管理工具的发展历史:......
  • Android Notes | 个人集成推送那点事(友盟/Mob(Flutter)/FCM)
    我们都曾羡慕别人,却忘了,我们也曾是别人羡慕的我们。前言最近的任务呐,真是让人蛋碎一地,各种被锤。不过比较nice的是,推送凑齐了,可以整理一篇咯~点滴积累吧。跟着老大~前期调研......
  • Go 语言机制之栈与指针
    原文作者:WilliamKennedy四哥水平有限,如有翻译或理解错误,烦请帮忙指出,感谢!原文如下:序言这个系列包含四篇文章,主要讲解Go言语指针、栈、堆、逃逸分析和值/指针语义背后的机......
  • 杂谈 | 在 macOS 上使用 Hugo + Coding 搭建个人博客
    文章目录​​前言​​​​旅途特色​​​​QuickStart​​​​一、Hugo配置以及使用​​​​1.Hugo下载安装​​​​2.创建本地网站​​​​3.下载喜欢的HugoTheme......