使用 viper 从 consul 读取配置文件
This commit is contained in:
parent
ac288f01ca
commit
033579702f
@ -8,8 +8,6 @@ import (
|
||||
|
||||
"github.com/cloudwego/kitex/pkg/klog"
|
||||
"github.com/kr/pretty"
|
||||
_ "github.com/spf13/viper"
|
||||
_ "github.com/spf13/viper/remote"
|
||||
"gopkg.in/validator.v2"
|
||||
"gopkg.in/yaml.v2"
|
||||
)
|
||||
|
@ -1,11 +1,8 @@
|
||||
package mysql
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/joho/godotenv"
|
||||
"github.com/suyiiyii/hertz101/app/user/conf"
|
||||
"os"
|
||||
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@ -20,8 +17,9 @@ func Init() {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
dsn := fmt.Sprintf(conf.GetConf().MySQL.DSN, os.Getenv("MYSQL_USER"), os.Getenv("MYSQL_PASSWORD"), os.Getenv("MYSQL_HOST"), os.Getenv("MYSQL_PORT"))
|
||||
DB, err = gorm.Open(mysql.Open(dsn),
|
||||
//dsn := fmt.Sprintf(conf.GetConf().MySQL.DSN, os.Getenv("MYSQL_USER"), os.Getenv("MYSQL_PASSWORD"), os.Getenv("MYSQL_HOST"), os.Getenv("MYSQL_PORT"))
|
||||
//DB, err = gorm.Open(mysql.Open(dsn),
|
||||
DB, err = gorm.Open(mysql.Open(conf.GetConf().MySQL.DSN),
|
||||
&gorm.Config{
|
||||
PrepareStmt: true,
|
||||
SkipDefaultTransaction: true,
|
||||
|
@ -1,6 +1,7 @@
|
||||
package conf
|
||||
|
||||
import (
|
||||
"github.com/spf13/viper"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@ -8,6 +9,8 @@ import (
|
||||
|
||||
"github.com/cloudwego/kitex/pkg/klog"
|
||||
"github.com/kr/pretty"
|
||||
_ "github.com/spf13/viper"
|
||||
_ "github.com/spf13/viper/remote"
|
||||
"gopkg.in/validator.v2"
|
||||
"gopkg.in/yaml.v2"
|
||||
)
|
||||
@ -67,6 +70,20 @@ func initConf() {
|
||||
}
|
||||
conf = new(Config)
|
||||
err = yaml.Unmarshal(content, conf)
|
||||
|
||||
// viper 获取远程配置测试
|
||||
err = viper.AddRemoteProvider("consul", conf.Registry.RegistryAddress[0], "USER")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
viper.SetConfigType("yaml")
|
||||
err = viper.ReadRemoteConfig()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
conf.MySQL.DSN = viper.GetString("MYSQL_DSN")
|
||||
|
||||
if err != nil {
|
||||
klog.Error("parse yaml error - %v", err)
|
||||
panic(err)
|
||||
|
Loading…
x
Reference in New Issue
Block a user