app-cloudep-trade-service/internal/svc/inject_mysql.go

49 lines
1.1 KiB
Go
Raw Normal View History

2024-10-29 08:17:31 +00:00
package svc
import (
"app-cloudep-trade-service/internal/config"
model "app-cloudep-trade-service/internal/model"
"database/sql"
"fmt"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
func mustDSN(c config.Config) string {
// 構建 DSN 字符串
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?parseTime=true&interpolateParams=%t",
c.DB.User,
c.DB.Password,
c.DB.Host,
c.DB.Port,
c.DB.Database,
c.DB.InterpolateParams,
)
}
func newDatabase(c config.Config) (*sql.DB, error) {
// 創建基礎的 *sql.DB 連接
db, err := sql.Open("mysql", mustDSN(c))
if err != nil {
logx.Error(fmt.Errorf("failed to connect to database: %w", err))
return nil, err
}
// 設置數據庫連接池參數
db.SetMaxIdleConns(c.DB.MaxIdleConns)
db.SetMaxOpenConns(c.DB.MaxOpenConns)
db.SetConnMaxLifetime(c.DB.ConnMaxLifetime)
return db, nil
}
// MustWalletModel 連線 wallet 時
func MustWalletModel(db *sql.DB) model.WalletModel {
// 創建並返回 *sqlx.SqlConn
sqlConn := sqlx.NewSqlConnFromDB(db)
return model.NewWalletModel(sqlConn)
}