[agent-go] 调整代码结构

This commit is contained in:
zeaslity
2023-03-30 14:26:11 +08:00
parent b01eb57ee5
commit 124143c6c6
17 changed files with 622 additions and 594 deletions

View File

@@ -1 +0,0 @@
package g

View File

@@ -1,172 +0,0 @@
package g
import (
"bytes"
"fmt"
"github.com/nacos-group/nacos-sdk-go/v2/clients"
"github.com/nacos-group/nacos-sdk-go/v2/clients/config_client"
"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
"github.com/nacos-group/nacos-sdk-go/v2/vo"
"github.com/spf13/viper"
"go.uber.org/zap"
"strconv"
"strings"
)
var log = G.LOG
var group = ""
func InitNacos(configFileName string) *viper.Viper {
v := parseAgentConfigFile(configFileName, nil)
group = v.GetString("spring.cloud.nacos.config.group")
// build the nacos connection
configClient := startNacosConnection(v)
// get all needed nacos config and merge
allNacosConfig := getAllNacosConfig(v, group, configClient)
for _, nacosConfigContent := range allNacosConfig {
log.Debug(fmt.Sprintf("nacos config conetent is %s", nacosConfigContent))
parseNacosConfigContend(nacosConfigContent, v)
}
log.Info(fmt.Sprintf("%s config read result are %v", configFileName, v.AllSettings()))
return v
}
func parseAgentConfigFile(configFileName string, v *viper.Viper) *viper.Viper {
// 使用Viper框架读取
if v == nil {
v = viper.New()
}
// 设置配置文件路径和名称
v.SetConfigName(configFileName)
v.AddConfigPath(".")
v.SetConfigType("yaml")
// 读取默认的总配置文件
err := v.ReadInConfig()
if err != nil {
panic(fmt.Errorf("fatal error config file: %s", err))
}
return v
}
func parseNacosConfigContend(configContent string, v *viper.Viper) *viper.Viper {
v.SetConfigType("yaml")
// use merge
err := v.MergeConfig(bytes.NewBuffer([]byte(configContent)))
if err != nil {
log.Error("nacos config contend read error !", zap.Error(err))
}
return v
}
func startNacosConnection(v *viper.Viper) config_client.IConfigClient {
serverAddr := v.GetString("spring.cloud.nacos.config.server-addr")
clientConfig := constant.ClientConfig{
//Endpoint: serverAddr,
NamespaceId: "",
TimeoutMs: v.GetUint64("spring.cloud.nacos.config.timeout"),
NotLoadCacheAtStart: true,
AppendToStdout: true,
UpdateCacheWhenEmpty: true,
//LogDir: "/tmp/nacos/log",
//CacheDir: "/tmp/nacos/cache",
Username: "nacos",
Password: "Superwmm.23",
}
split := strings.Split(serverAddr, ":")
if len(split) != 2 {
log.Error("nacos server addr error!")
}
port, _ := strconv.ParseUint(split[1], 10, 64)
serverConfigs := []constant.ServerConfig{
{
IpAddr: split[0],
Port: port,
GrpcPort: port + 1000,
},
}
// Another way of create config client for dynamic configuration (recommend)
configClient, err := clients.NewConfigClient(
vo.NacosClientParam{
ClientConfig: &clientConfig,
ServerConfigs: serverConfigs,
},
)
if err != nil {
panic(err)
}
return configClient
}
func getAllNacosConfig(v *viper.Viper, group string, configClient config_client.IConfigClient) []string {
result := make([]string, 0)
// main nacos configs
mainNacosConfigFileName := v.GetString("spring.application.name") + "-" + v.GetString("spring.profiles.active") + "." + v.GetString("spring.cloud.nacos.config.file-extension")
log.Debug(fmt.Sprintf("main nacos config file name is %s", mainNacosConfigFileName))
configContent := getConfig(mainNacosConfigFileName, group, configClient)
result = append(result, configContent)
// additional nacos config
additionalNacosConfig := v.Get("spring.cloud.nacos.config.extension-configs")
// 增加断言判定map的类型
m, ok := additionalNacosConfig.([]interface{})
if !ok {
fmt.Println("additionalNacosConfig is not a slice")
return nil
}
for _, addConfigMap := range m {
realMap, _ := addConfigMap.(map[string]interface{})
// 拿到配置的Key
dataId := realMap["data-id"].(string)
group := realMap["group"].(string)
// 查询
config := getConfig(dataId, group, configClient)
result = append(result, config)
}
return result
}
// getConfig 从Nacos中获取相应的
func getConfig(dataId string, group string, configClient config_client.IConfigClient) string {
log.Debug(fmt.Sprintf("nacos config get method dataID is %s, group is %s", dataId, group))
content, err := configClient.GetConfig(vo.ConfigParam{
DataId: dataId,
Group: group,
})
if err != nil {
log.Error("nacos config get error !", zap.Error(err))
}
log.Debug(fmt.Sprintf("dataId %s , group %s, nacos config content is %s", dataId, group, content))
return content
}

View File

@@ -1,16 +1,15 @@
package g
import (
"agent-go/config"
logger2 "agent-go/logger"
"github.com/panjf2000/ants/v2"
"github.com/spf13/viper"
)
type Global struct {
LOG *Logger
NacosConfig *viper.Viper
AgentServerInfo *config.AgentServerInfo
P *ants.Pool
AgentHasRegister bool
NacosConfig *viper.Viper
P *ants.Pool
}
const (
@@ -21,21 +20,17 @@ const (
InitOmType = "INIT"
)
var logger, _ = NewLogger()
var pool, _ = ants.NewPool(100, ants.WithNonblocking(true), ants.WithLogger(logger))
var pool, _ = ants.NewPool(100, ants.WithNonblocking(true), ants.WithLogger(logger2.Log))
var G = NewGlobal(
logger,
pool,
)
// NewGlobal NewGlobal构造函数返回一个新的Global实例其中包含指定的Logger。
func NewGlobal(logger *Logger, pool *ants.Pool) *Global {
func NewGlobal(pool *ants.Pool) *Global {
return &Global{
LOG: logger,
NacosConfig: nil,
AgentServerInfo: nil,
P: pool,
AgentHasRegister: false,
NacosConfig: nil,
P: pool,
}
}

View File

@@ -1,75 +0,0 @@
package g
import (
"fmt"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// Logger struct represents a zap-based logger.
type Logger struct {
*zap.Logger
}
// NewLogger creates a new Logger instance.
func NewLogger() (*Logger, error) {
config := zap.Config{
Encoding: "json",
Level: zap.NewAtomicLevelAt(zap.DebugLevel),
OutputPaths: []string{"stdout"}, // 输出到控制台
ErrorOutputPaths: []string{"stderr"},
EncoderConfig: zapcore.EncoderConfig{
MessageKey: "message",
LevelKey: "level",
TimeKey: "time",
//CallerKey: "caller",
EncodeLevel: zapcore.CapitalColorLevelEncoder,
EncodeTime: zapcore.RFC3339TimeEncoder,
//EncodeCaller: zapcore.FullCallerEncoder,
},
}
logger, err := config.Build()
if err != nil {
return nil, err
}
return &Logger{logger}, nil
}
func (l *Logger) Printf(msg string, args ...interface{}) {
l.Logger.Info(fmt.Sprintf("%s ==> %v", msg, args))
}
// Debug logs a debug message.
func (l *Logger) Debug(msg string, fields ...zap.Field) {
l.Logger.Debug(msg, fields...)
}
func (l *Logger) DebugF(msg string, args ...interface{}) {
l.Logger.Debug(fmt.Sprintf(msg, args...))
}
// Info logs an info message.
func (l *Logger) Info(msg string, fields ...zap.Field) {
l.Logger.Info(msg, fields...)
}
// InfoF logs an info message with format
func (l *Logger) InfoF(msg string, args ...interface{}) {
l.Logger.Info(fmt.Sprintf(msg, args...))
}
// Warn logs a warning message.
func (l *Logger) Warn(msg string, fields ...zap.Field) {
l.Logger.Warn(msg, fields...)
}
// Error logs an error message.
func (l *Logger) Error(msg string, fields ...zap.Field) {
l.Logger.Error(msg, fields...)
}
// Fatal logs a fatal message and exits the program with a non-zero status code.
func (l *Logger) Fatal(msg string, fields ...zap.Field) {
l.Logger.Fatal(msg, fields...)
}