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

39 lines
798 B
Go
Raw Normal View History

2024-10-29 08:17:31 +00:00
package svc
import (
"app-cloudep-trade-service/internal/config"
"database/sql"
"fmt"
"github.com/zeromicro/go-zero/core/logx"
)
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
}