六.库存微服务( inventory_srv)
1.项目初始化
1.1添加配置文件
host: '192.168.0.4'
port: 8848
namespace: 'ba14206d-403f-4377-b7e7-70a3e8fa2bbf'
user: 'nacos'
password: 'nacos'
dataid: 'inventory-srv.json'
group: 'dev'
1.2配置文件结构体创建
inventory-srv/config/config.go
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"`
Tags []string `mapstructure:"tags" json:"tags"`
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"`
}
1.3建立全局变量
inventory-srv/global/global.go
package global
import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"gorm.io/gorm/schema"
"log"
"mxshop_srvs/inventory_srv/config"
"os"
"time"
)
var (
DB *gorm.DB
ServerConfig config.ServerConfig
NacosConfig config.NacosConfig
)
1.4配置文件初始化
inventory-srv/initialize/config.go
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_srvs/inventory_srv/global"
)
func GetEnvInfo(env string) bool {
viper.AutomaticEnv()
return viper.GetBool(env)
//刚才设置的环境变量 想要生效 我们必须得重启goland
}
func InitConfig() {
//从配置文件中读取出对应的配置
debug := GetEnvInfo("MXSHOP_DEBUG")
configFilePrefix := "config"
configFileName := fmt.Sprintf("inventory_srv/%s-pro.yaml", configFilePrefix)
if debug {
configFileName = fmt.Sprintf("inventory_srv/%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,需要去设置这个struct的tag
err = json.Unmarshal([]byte(content), &global.ServerConfig)
if err != nil {
zap.S().Fatalf("读取nacos配置失败: %s", err.Error())
}
fmt.Println(&global.ServerConfig)
}
inventory-srv/initialize/db.go
package initialize
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"gorm.io/gorm/schema"
"log"
"mxshop_srvs/inventory_srv/global"
"os"
"time"
)
func InitDB() {
c := global.ServerConfig.MysqlInfo
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
c.User, c.Password, c.Host, c.Port, c.Name)
newLogger := logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
logger.Config{
SlowThreshold: time.Second, // 慢 SQL 阈值
LogLevel: logger.Info, // Log level
Colorful: true, // 禁用彩色打印
},
)
// 全局模式
var err

最低0.47元/天 解锁文章
177

被折叠的 条评论
为什么被折叠?



