52 lines
1.3 KiB
Go
52 lines
1.3 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"fmt"
|
|
"log"
|
|
"time"
|
|
|
|
// 导入MySQL驱动
|
|
_ "github.com/go-sql-driver/mysql"
|
|
)
|
|
|
|
// MySQLDB MySQL数据库连接结构体
|
|
type MySQLDB struct {
|
|
baseDB
|
|
}
|
|
|
|
// NewMySQLDB 创建MySQL数据库连接实例
|
|
func NewMySQLDB(cfg Config) (DB, error) {
|
|
// 构建MySQL连接字符串
|
|
// 格式: username:password@tcp(host:port)/database?charset=utf8mb4&parseTime=True&loc=Local
|
|
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=True&loc=Local",
|
|
cfg.Username, cfg.Password, cfg.Host, cfg.Port, cfg.Database, cfg.Charset)
|
|
|
|
// 打开数据库连接
|
|
db, err := sql.Open("mysql", dsn)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to open mysql connection: %w", err)
|
|
}
|
|
|
|
// 配置连接池
|
|
db.SetMaxOpenConns(20) // 最大打开连接数
|
|
db.SetMaxIdleConns(10) // 最大空闲连接数
|
|
db.SetConnMaxLifetime(30 * time.Minute) // 连接最大生命周期
|
|
db.SetConnMaxIdleTime(10 * time.Minute) // 连接最大空闲时间
|
|
|
|
// 测试连接
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
|
|
if err := db.PingContext(ctx); err != nil {
|
|
return nil, fmt.Errorf("failed to ping mysql: %w", err)
|
|
}
|
|
|
|
log.Println("MySQL connection established successfully")
|
|
|
|
return &MySQLDB{
|
|
baseDB: baseDB{db: db},
|
|
}, nil
|
|
}
|