first commit
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
package mysqlmodel
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"git.lzcwy.cn/zhengchiliu/zt-closet-backend/pkg/setting"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/plugin/soft_delete"
|
||||
)
|
||||
|
||||
type Model struct {
|
||||
ID int64 `gorm:"column:id;primaryKey"` // 主键ID
|
||||
CreatedAt int64 `gorm:"column:created_at"` // 创建时间
|
||||
UpdatedAt int64 `gorm:"column:updated_at"` // 更新时间
|
||||
DeletedAt soft_delete.DeletedAt `gorm:"column:deleted_at"` // 删除时间
|
||||
CreatedBy int64 `gorm:"column:created_by"` // 创建人
|
||||
UpdatedBy int64 `gorm:"column:updated_by"` // 更新人
|
||||
DeletedBy int64 `gorm:"column:deleted_by"` // 删除人
|
||||
}
|
||||
|
||||
// NewMysqlEngine 根据配置创建 GORM MySQL 连接并完成连接池初始化。
|
||||
func NewMysqlEngine(mysqlSetting *setting.MysqlSettingS) (*gorm.DB, error) {
|
||||
s := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local&timeout=10s&readTimeout=10s&writeTimeout=10s",
|
||||
mysqlSetting.UserName,
|
||||
mysqlSetting.Password,
|
||||
mysqlSetting.Host,
|
||||
mysqlSetting.Port,
|
||||
mysqlSetting.DBName,
|
||||
)
|
||||
db, err := gorm.Open(mysql.Open(s), &gorm.Config{})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sqlDB, err := db.DB()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sqlDB.SetMaxIdleConns(mysqlSetting.MaxIdleConns)
|
||||
sqlDB.SetMaxOpenConns(mysqlSetting.MaxOpenConns)
|
||||
sqlDB.SetConnMaxLifetime(time.Duration(mysqlSetting.ConnMaxLifeTime) * time.Second)
|
||||
sqlDB.SetConnMaxIdleTime(time.Duration(mysqlSetting.ConnMaxIdleTime) * time.Second)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := sqlDB.PingContext(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return db, nil
|
||||
}
|
||||
Reference in New Issue
Block a user