fusenapi/utils/fsconfig/config.go
2023-09-19 19:16:26 +08:00

186 lines
4.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package fsconfig
import (
"log"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/nacos-group/nacos-sdk-go/v2/clients"
"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
"github.com/nacos-group/nacos-sdk-go/v2/vo"
"github.com/zeromicro/go-zero/core/conf"
"gopkg.in/yaml.v2"
)
type EnvConfig struct {
NacosServers []string `yaml:"nacos"`
UserName string `yaml:"username"`
Password string `yaml:"password"`
NamespaceId string `yaml:"namespace"`
DataId string `yaml:"dataid"`
Group string `yaml:"group"`
ProxyServer struct {
KeyFile string `yaml:"key"`
PemFile string `yaml:"pem"`
} `yaml:"proxyserver"`
ServerBackend struct {
KeyFile string `yaml:"key"`
PemFile string `yaml:"pem"`
} `yaml:"serverbackend"`
}
var optPathDirs = []string{"/opt", "./", "../", "../../"}
var nacosConfig *EnvConfig
func GetEnvCofing() *EnvConfig {
if nacosConfig != nil {
return nacosConfig
}
for _, optDir := range optPathDirs {
if optDir[len(optDir)-1] != '/' {
optDir = optDir + "/"
}
for _, yname := range []string{"env.yaml", "env.yml"} {
f, err := os.Open(optDir + yname)
if err != nil {
// log.Println(err)
continue
}
cfg := &EnvConfig{}
err = yaml.NewDecoder(f).Decode(&cfg)
if err != nil {
// log.Println(err)
continue
}
nacosConfig = cfg
return nacosConfig
}
}
panic("Can't find env.yaml or env.yml in the specified directories")
}
func init() {
}
func StartNacosConfig(configFile string, cfg any, OnChange func(namespace, group, dataId, data string)) {
env := GetEnvCofing()
// 创建serverConfig
// 支持多个;至少一个ServerConfig
var serverConfig []constant.ServerConfig
for _, s := range env.NacosServers {
sp := strings.Split(s, ":")
host := sp[0]
port, err := strconv.ParseUint(sp[1], 10, 64)
if err != nil {
panic(err)
}
serverConfig = append(serverConfig, constant.ServerConfig{
IpAddr: host,
Port: port,
})
}
// 创建clientConfig
clientConfig := constant.ClientConfig{
NamespaceId: env.NamespaceId, // 如果需要支持多namespace我们可以场景多个client,它们有不同的NamespaceId。当namespace是public时此处填空字符串。
TimeoutMs: 50000,
NotLoadCacheAtStart: true,
LogLevel: "debug",
LogDir: "/tmp/nacos/log",
CacheDir: "/tmp/nacos/cache",
Username: env.UserName,
Password: env.Password,
}
// 创建服务发现客户端的另一种方式 (推荐)
// namingClient, err := clients.NewNamingClient(
// vo.NacosClientParam{
// ClientConfig: &clientConfig,
// ServerConfigs: serverConfig,
// },
// )
// if err != nil {
// log.Fatalf("初始化nacos失败: %s", err.Error())
// }
// log.Println(namingClient)
// 创建 Nacos 配置客户端
configClient, err := clients.CreateConfigClient(map[string]interface{}{
"clientConfig": clientConfig,
"serverConfigs": serverConfig,
})
if err != nil {
log.Fatalf("Failed to create Nacos config client: %v", err)
}
cfgYamls := strings.Split(configFile, "/")
cfgYaml := cfgYamls[len(cfgYamls)-1]
yamlExt := filepath.Ext(cfgYaml)
if !(yamlExt == ".yaml" || yamlExt == ".yml") {
log.Panic(configFile)
}
// 获取配置
content, err := configClient.GetConfig(vo.ConfigParam{
DataId: cfgYaml,
Group: env.Group,
OnChange: OnChange,
})
if err != nil {
log.Fatalf("Failed to get config from Nacos: %v", err)
}
var selfConfig map[string]interface{} = make(map[string]interface{})
err = yaml.Unmarshal([]byte(content), &selfConfig)
if err != nil {
log.Fatalf("Failed to get config from Nacos: %v", err)
}
content, err = configClient.GetConfig(vo.ConfigParam{
DataId: "common",
Group: env.Group,
OnChange: nil,
})
if err != nil {
log.Fatalf("Failed to get config from Nacos: %v", err)
}
var commonConfig map[string]interface{} = make(map[string]interface{})
err = yaml.Unmarshal([]byte(content), &commonConfig)
if err != nil {
log.Fatalf("Failed to get config from Nacos: %v", err)
}
for k, v := range commonConfig {
selfConfig[k] = v
}
data, err := yaml.Marshal(selfConfig)
if err != nil {
log.Fatalf("Failed to get config from Nacos: %v", err)
}
log.Print("加载成功: ", cfgYaml, "\n环境: ", env.Group, "\n", string(data))
err = conf.LoadFromYamlBytes(data, cfg)
if err != nil {
log.Fatalf("Failed to get config content from Nacos: %v", err)
}
// log.Println(content)
}