go-mciro系列(四)使用nacos作为配置中心_go使用nacos
编写获取配置代码
获取配置的方法直接使用的官方提供的代码,与框架其实没有多大关系,官方文档:https://github.com/nacos-group/nacos-sdk-go
项目目录:
├─microuser
│ ├─config
│ ├─handler
│ ├─proto
│ │ └─microuser
│ └─subscriber
编写config/setting.go
package config
import (
"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"
"gopkg.in/yaml.v2"
"log"
)
type Conf struct {
App App `yaml:"app"`
}
// 这个结构体对应配置文件中的app配置
type App struct {
Name string `yaml:"name"`
Port int64 `yaml:"port"`
}
var GlobalConf Conf
func InitSetting() {
clientConfig := constant.ClientConfig{
NamespaceId: "9dbcec67-96b5-45c9-8e80-737342fac52d",
TimeoutMs: 5000,
NotLoadCacheAtStart: true,
LogDir: "D:/alidata/logs/nacos/log",
CacheDir: "D:/alidata/logs/nacos/cache",
RotateTime: "1h",
MaxAge: 3,
LogLevel: "debug",
}
// At least one ServerConfig
serverConfigs := []constant.ServerConfig{
{
IpAddr: "127.0.0.1",
ContextPath: "/nacos",
Port: 8848,
Scheme: "http",
},
}
configClient, err := clients.NewConfigClient(
vo.NacosClientParam{
ClientConfig: &clientConfig,
ServerConfigs: serverConfigs,
},
)
content, err := configClient.GetConfig(vo.ConfigParam{
DataId: "microuser",
Group: "DEFAULT\_GROUP"})
if err != nil {
log.Fatalf("获取配置信息出错,", err)
}
err = MapTo(content)
if err != nil {
log.Fatalf("yaml解析配置文件出错,", err)
}
// 动态监听
err = configClient.ListenConfig(vo.ConfigParam{
DataId: "microuser",
Group: "DEFAULT\_GROUP",
OnChange: func(namespace, group, dataId, data string) {
err = MapTo(data)
if err != nil {
log.Printf("监听配置出错,", err)
}
},
})
if err != nil {
log.Fatalf("动态监听配置文件出错,", err)
}
}
func MapTo(content string) (err error) {
err = yaml.Unmarshal([]byte(content), &GlobalConf)
return
}
修改main.go
package main
import (
"gitee.com/zjq528/microuser/config"
"gitee.com/zjq528/microuser/handler"
microuser "gitee.com/zjq528/microuser/proto/microuser"
"gitee.com/zjq528/microuser/subscriber"
"github.com/micro/go-micro/v2"
log "github.com/micro/go-micro/v2/logger"
)
![img](https://img-blog.csdnimg.cn/img_convert/86a6b119e66574063bfe4adf52ec3838.png)
![img](https://img-blog.csdnimg.cn/img_convert/83bafb05071e458004cb50019f9c6ef4.png)
**网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**
加入社区》https://bbs.csdn.net/forums/4304bb5a486d4c3ab8389e65ecb71ac0
**网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**
加入社区》https://bbs.csdn.net/forums/4304bb5a486d4c3ab8389e65ecb71ac0