83 lines
2.3 KiB
Go
83 lines
2.3 KiB
Go
package repository
|
|
|
|
import (
|
|
"ai-gateway/common/config"
|
|
"ai-gateway/common/constant"
|
|
"database/sql"
|
|
"github.com/google/uuid"
|
|
"github.com/labstack/echo/v4"
|
|
"os"
|
|
"time"
|
|
|
|
fbcontext "code.freebrio.com/fb-go/lib/context"
|
|
"code.freebrio.com/fb-go/lib/fbl"
|
|
"code.freebrio.com/fb-go/lib/gorm/logger"
|
|
|
|
_ "github.com/spf13/viper/remote"
|
|
"gorm.io/driver/mysql"
|
|
"gorm.io/gorm"
|
|
loglevel "gorm.io/gorm/logger"
|
|
)
|
|
|
|
var myConf mysqlConf
|
|
var instanceErr error
|
|
var Db = getInstance()
|
|
|
|
type mysqlConf struct {
|
|
Dsn string `mapstructure:"dsn" json:"dsn" yaml:"dsn"` // dns
|
|
MaxIdleConn int `mapstructure:"maxIdleConn" json:"maxIdleConn" yaml:"maxIdleConn"` //
|
|
MaxOpenConn int `mapstructure:"maxOpenConn" json:"maxOpenConn" yaml:"maxOpenConn"` //
|
|
|
|
ConnMaxLifetime int `mapstructure:"connMaxLifetime" json:"connMaxLifetime" yaml:"connMaxLifetime"`
|
|
}
|
|
|
|
func getInstance() *gorm.DB {
|
|
// unmarshal config
|
|
ll := logger.NewZapLogger()
|
|
ll = ll.LogMode(loglevel.Warn)
|
|
db, instanceErr := gorm.Open(mysql.Open(config.Instance.Mysql.Dsn), &gorm.Config{
|
|
Logger: ll,
|
|
SkipDefaultTransaction: true,
|
|
})
|
|
|
|
if instanceErr != nil {
|
|
fbl.Log().Sugar().Errorf("mysql_getInstance instanceErr: %v", instanceErr)
|
|
os.Exit(-1)
|
|
}
|
|
|
|
var sqlDB *sql.DB
|
|
sqlDB, instanceErr = db.DB()
|
|
if instanceErr != nil {
|
|
fbl.Log().Sugar().Errorf("mysql_getInstance sqlDB: %v", instanceErr)
|
|
os.Exit(-1)
|
|
}
|
|
|
|
// SetMaxIdleConns 设置空闲连接池中连接的最大数量
|
|
sqlDB.SetMaxIdleConns(config.Instance.Mysql.ConnMaxLifetime)
|
|
// SetMaxOpenConns 设置打开数据库连接的最大数量。
|
|
sqlDB.SetMaxOpenConns(config.Instance.Mysql.MaxOpenConn)
|
|
// SetConnMaxLifetime 设置了连接可复用的最大时间。
|
|
sqlDB.SetConnMaxLifetime(time.Duration(config.Instance.Mysql.MaxIdleConn) * time.Second)
|
|
return db
|
|
}
|
|
|
|
func GetDB() (*gorm.DB, error) {
|
|
return Db, instanceErr
|
|
}
|
|
|
|
func GetFbc(c *echo.Context) fbcontext.GormWithZap {
|
|
traceId := (*c).Request().Header.Get(echo.HeaderXRequestID)
|
|
if traceId == "" {
|
|
//端上使用 X-Request-ID
|
|
traceId = (*c).Request().Header.Get(constant.XRequestId)
|
|
|
|
if traceId == "" {
|
|
traceId = uuid.New().String()
|
|
(*c).Request().Header.Set(echo.HeaderXRequestID, traceId)
|
|
}
|
|
}
|
|
|
|
fbc := fbcontext.BackgroundWithZapAndGorm(GetDB, fbcontext.ZapTraceID(""))
|
|
return fbc
|
|
}
|