当前位置:网站首页>18. Distributed configuration center nacos
18. Distributed configuration center nacos
2022-08-01 19:30:00 【Endless character】
目录
一、为什么需要分布式配置中心
二、配置中心选型
- The current mainstream distributed configuration center:spring cloud config、apollo和nacos;spring cloud config属于java的spring体系,我们就考虑apollo和nacos
- apollo和nacos:apolloIt is Ctrip open source、nacos是阿里开源
- a、apollo大而全,功能完善;nacos小而全,can be compareddjango和flask的区别
- b、部署nacos更加简单
- c、nacos不止支持配置中心还支持服务注册和发现
- d、都支持各种语言,不过apollo是第三方支持的,nacos是官方支持各种语言
- nacos官网:https://nacos.io/zh-cn/
- apollo的git地址:https://github.com/apolloconfig/apollo
- apollo和nacos功能对比
功能点 | apollo | nacos |
---|---|---|
开源时间 | 2016.5 | 2018.6 |
配置实时推送 | 支持(http长轮询) | 支持(http长轮询) |
配置回滚 | 支持 | 支持 |
灰度发布 | 支持 | 待支持 |
权限管理 | 支持 | 支持 |
多集群 | 支持 | 支持 |
监听查询 | 支持 | 支持 |
多语言 | 主流语言 | 主流语言(官方支持) |
通讯协议 | http | http |
三、nacos安装与访问
- nacosInstallation and Access Reference:https://blog.csdn.net/qq23001186/article/details/126084869
四、api获取nacos配置
1 - nacos配置
- A new namespace needs to be createdusers
- 在usersUnder the namespace is the previous oneuser_web和user_srv添加配置集:因为有dev和pro,所以需要新建4个配置集
2 - go nacos
- nacos-sdk-go地址:https://github.com/nacos-group/nacos-sdk-go
- nacos-sdk-go中文文档地址:https://github.com/nacos-group/nacos-sdk-go/blob/master/README_CN.md
- go nacos需求分析
- ①.configuration can be obtained
- ②.Can monitor configuration file modifications
- ③.nacosThat is, a configuration center,也是一个注册中心(我们使用consul作为注册中心,主要是因为consul是goDeveloped and focused on the registry)
- go nacosImplement configuration reading and monitoring configuration changes
package main
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"
"time"
)
func main() {
sc := []constant.ServerConfig{
{
IpAddr: "192.168.124.51",
Port: 8848,
},
}
// 创建clientConfig
cc := constant.ClientConfig{
NamespaceId: "90dec033-6f9a-4ab2-97e5-fd60de1743c9", // 如果需要支持多namespace,我们可以场景多个client,它们有不同的NamespaceId.当namespace是public时,此处填空字符串.
TimeoutMs: 5000,
NotLoadCacheAtStart: true,
LogDir: "tmp/nacos/log", //去掉tmp前面的/,This will save to the current project directory by default
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: "user_web.yaml",
Group: "dev"})
if err != nil {
panic(err)
}
fmt.Println(content) //字符串 - yaml
//监听配置修改
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)
}
- CacheDir的作用:
- 配置了CacheDir的时候,It will be generated under the local projectCacheDir的目录
- 假设nacos的ipWe have misconfigured the address,无法访问nacos;If we have configurationCachaDir,Then the local configuration information will be read
五、gin集成nacos
1 - nacosconfiguration maps togo的struct
- 需求分析:因为go本身集成了json,而yaml需要使用第三方库,We directly modify the previous configuration tojson
- YAML TO JSON在线转换:http://json2yaml.com/convert-yaml-to-json
- nacos中添加user_web.json配置集
{
"name": "user_web",
"port": 8081,
"user_srv": {
"host": "127.0.0.1",
"port": 50051,
"name": "user_srv"
},
"jwt": {
"key": "VYLDYq3&hGWjWqF$K1ih"
},
"sms": {
"key": "",
"secrect": ""
},
"redis": {
"host": "192.168.124.51",
"port": 6379,
"expire": 300
},
"consul": {
"host": "192.168.124.51",
"port": 8500
}
}
2 - user_web读取nacos的config
- user_web/config/config.go:添加NacosConfig对象
package config
type UserSrvConfig struct {
Host string `mapstructure:"host" json:"host"`
Port int `mapstructure:"port" json:"port"`
Name string `mapstructure:"name" json:"name"`
}
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 ConsulConfig struct {
Host string `mapstructure:"host" json:"host"`
Port int `mapstructure:"port" json:"port"`
}
type RedisConfig struct {
Host string `mapstructure:"host" json:"host"`
Port int `mapstructure:"port" json:"port"`
Expire int `mapstructure:"expire" json:"expire"`
}
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"`
AliSmsInfo AliSmsConfig `mapstructure:"sms" json:"sms"`
RedisInfo RedisConfig `mapstructure:"redis" json:"redis"`
ConsulInfo ConsulConfig `mapstructure:"consul" json:"consul"`
}
type NacosConfig struct {
Host string `mapstructure:"host"`
Port uint64 `mapstructure:"port"`
Namespace string `mapstructure:"namespace"`
User string `mapstructure:"user"`
Password string `mapstructure:"password"`
DataId string `mapstructure:"dataid"`
Group string `mapstructure:"group"`
}
- user_web/global/global.go:添加全局NacosConfig对象
package global
import (
ut "github.com/go-playground/universal-translator"
"web_api/user_web/config"
"web_api/user_web/proto"
)
var (
Trans ut.Translator
ServerConfig *config.ServerConfig = &config.ServerConfig{
}
UserSrvClient proto.UserClient
NacosConfig *config.NacosConfig = &config.NacosConfig{
}
)
- yaml修改为nacos的配置
//config_debug.yaml
host: '192.168.124.51'
port: 8848
namespace: '90dec033-6f9a-4ab2-97e5-fd60de1743c9'
user: 'nacos'
password: 'nacos'
dataid: 'user_web.json'
group: 'dev'
//config_pro.yaml
host: '192.168.124.51'
port: 8848
namespace: '90dec033-6f9a-4ab2-97e5-fd60de1743c9'
user: 'nacos'
password: 'nacos'
dataid: 'user_web.json'
group: 'pro'
- user_web/initialize/init_config.go:
- 读取nacos的配置
- 通过nacosRead and map to the configuration centerServerConfig
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"
"web_api/user_web/global"
)
func GetEnvInfo(env string) bool {
viper.AutomaticEnv()
return viper.GetBool(env)
//刚才设置的环境变量 想要生效 我们必须得重启goland
}
func InitConfig() {
debug := GetEnvInfo("DEV_CONFIG")
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) //字符串 - yaml
//想要将一个json字符串转换成struct,Need to set this upstruct的tag
err = json.Unmarshal([]byte(content), &global.ServerConfig)
if err != nil {
zap.S().Fatalf("读取nacos配置失败: %s", err.Error())
}
fmt.Println(&global.ServerConfig)
}
六、service集成nacos
1 - 配置nacos
2 - user_srv读取nacos的config
- yaml修改为nacos的配置
//config_debug.yaml
host: '192.168.124.51'
port: 8848
namespace: '90dec033-6f9a-4ab2-97e5-fd60de1743c9'
user: 'nacos'
password: 'nacos'
dataid: 'user_srv.json'
group: 'dev'
//config_pro.yaml
host: '192.168.124.51'
port: 8848
namespace: '90dec033-6f9a-4ab2-97e5-fd60de1743c9'
user: 'nacos'
password: 'nacos'
dataid: 'user_srv.json'
group: 'pro'
- user_srv/config/config.go:新增NacosConfig对象
package config
type MysqlConfig struct {
Host string `mapstructure:"host" json:"host"`
Port int `mapstructure:"port" json:"port"`
Name string `mapstructure:"db" json:"db"`
User string `mapstructure:"user" json:"user"`
Password string `mapstructure:"password" json:"password"`
}
type ConsulConfig struct {
Host string `mapstructure:"host" json:"host"`
Port int `mapstructure:"port" json:"port"`
}
type ServerConfig struct {
Name string `mapstructure:"name" json:"name"`
MysqlInfo MysqlConfig `mapstructure:"mysql" json:"mysql"`
ConsulInfo ConsulConfig `mapstructure:"consul" json:"consul"`
}
type NacosConfig struct {
Host string `mapstructure:"host"`
Port uint64 `mapstructure:"port"`
Namespace string `mapstructure:"namespace"`
User string `mapstructure:"user"`
Password string `mapstructure:"password"`
DataId string `mapstructure:"dataid"`
Group string `mapstructure:"group"`
}
- user_srv/global/global.go:添加全局对象NacosConfig
package global
import (
"gorm.io/gorm"
"nd/user_srv/config"
)
var (
DB *gorm.DB
ServerConfig config.ServerConfig
NacosConfig config.NacosConfig
)
- user_srv/initialize/init_config.go:
- 读取nacos的配置
- 通过nacosRead and map to the configuration centerServerConfig
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"
"nd/user_srv/global"
)
func GetEnvInfo(env string) bool {
viper.AutomaticEnv()
return viper.GetBool(env)
//刚才设置的环境变量 想要生效 我们必须得重启goland
}
func InitConfig() {
//从配置文件中读取出对应的配置
debug := GetEnvInfo("DEV_CONFIG")
configFilePrefix := "config"
configFileName := fmt.Sprintf("%s_pro.yaml", configFilePrefix)
if debug {
configFileName = fmt.Sprintf("%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) //字符串 - yaml
//想要将一个json字符串转换成struct,Need to set this upstruct的tag
err = json.Unmarshal([]byte(content), &global.ServerConfig)
if err != nil {
zap.S().Fatalf("读取nacos配置失败: %s", err.Error())
}
fmt.Println(&global.ServerConfig)
}
七、完整源码
- 附录:资源包含了YApi的json导入,nacosconfiguration set import
- user_srv/main.go:Health monitoring and registration objectsipThe address needs to be changed to the local oneip地址
- user_srv/main.go:Health monitoring and registration objectsipThe address needs to be changed to the local oneip地址
边栏推荐
- 数值矩阵的图形表示
- ExcelPatternTool: Excel表格-数据库互导工具
- Win11校园网无法连接怎么办?Win11连接不到校园网的解决方法
- 如何记录分析你的炼丹流程—可视化神器Wandb使用笔记【1】
- Source code analysis of GZIPOutputStream class
- 小白系统初始化配置资源失败怎么办
- PanGu-Coder:函数级的代码生成模型
- MLX90640 Infrared Thermal Imager Temperature Measurement Module Development Notes (Complete)
- 【pyqt5】自定义控件 实现能够保持长宽比地缩放子控件
- The solution to the vtk volume rendering code error (the code can run in vtk7, 8, 9), and the VTK dataset website
猜你喜欢
Become a Contributor in 30 minutes | How to participate in OpenHarmony's open source contributions in multiple ways?
百度无人驾驶商业化已“上路”
力扣刷题之移动零
log factory (detail)
Keras deep learning practice - traffic sign recognition
Shell script topic (07): file from cfs to bos
明尼苏达大学团队结合高通量实验与机器学习,实现有效可预测的特定位点重组过程,可调节基因编辑速度
在全志V853开发板试编译QT测试
Gradle系列——Gradle文件操作,Gradle依赖(基于Gradle文档7.5)day3-1
OSPO 五阶段成熟度模型解析
随机推荐
#yyds dry goods inventory# Interview must brush TOP101: the last k nodes in the linked list
Pytorch模型训练实用教程学习笔记:三、损失函数汇总
DAO开发教程【WEB3.0】
Shell script topic (07): file from cfs to bos
八百客、销售易、纷享销客各行其道
Multi-Party Threshold Private Set Intersection with Sublinear Communication-2021:解读
屏:全贴合工艺之GFF、OGS、Oncell、Incell
TestNG多个xml进行自动化测试
力扣刷题之合并两个有序数组
mysql自增ID跳跃增长解决方案
数据库系统原理与应用教程(070)—— MySQL 练习题:操作题 101-109(十四):查询条件练习
网络不通?服务丢包?这篇 TCP 连接状态详解及故障排查,收好了~
在GBase 8c数据库后台,使用什么样的命令来对gtm、dn节点进行主备切换的操作?
首篇 NLP 领域图神经网络综述:127 页,从图构建到实际应用面面观
不恰当Equatable协议==方法的实现对SwiftUI中@State修饰属性的影响
英国伦敦大学|眼科强化学习:潜在应用和实施挑战
安装win32gui失败,解决问题
cf:D. Magical Array【数学直觉 + 前缀和的和】
Combining two ordered arrays
C#/VB.NET Extract table from PDF