59 lines
1.4 KiB
Go
59 lines
1.4 KiB
Go
|
|
package persistence
|
||
|
|
|
||
|
|
import (
|
||
|
|
"database/sql"
|
||
|
|
"fmt"
|
||
|
|
"time"
|
||
|
|
)
|
||
|
|
|
||
|
|
// DBConfig 数据库配置
|
||
|
|
type DBConfig struct {
|
||
|
|
// DriverName 数据库驱动名称,如 "postgres", "mysql", "sqlite3" 等
|
||
|
|
DriverName string
|
||
|
|
// DSN 数据源名称(连接字符串)
|
||
|
|
DSN string
|
||
|
|
// MaxOpenConns 最大打开连接数
|
||
|
|
MaxOpenConns int
|
||
|
|
// MaxIdleConns 最大空闲连接数
|
||
|
|
MaxIdleConns int
|
||
|
|
// ConnMaxLifetime 连接最大生命周期
|
||
|
|
ConnMaxLifetime time.Duration
|
||
|
|
// ConnMaxIdleTime 连接最大空闲时间
|
||
|
|
ConnMaxIdleTime time.Duration
|
||
|
|
}
|
||
|
|
|
||
|
|
// DefaultDBConfig 返回默认数据库配置
|
||
|
|
func DefaultDBConfig(driverName, dsn string) DBConfig {
|
||
|
|
return DBConfig{
|
||
|
|
DriverName: driverName,
|
||
|
|
DSN: dsn,
|
||
|
|
MaxOpenConns: 25,
|
||
|
|
MaxIdleConns: 5,
|
||
|
|
ConnMaxLifetime: time.Hour,
|
||
|
|
ConnMaxIdleTime: 10 * time.Minute,
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// NewDB 创建并配置数据库连接
|
||
|
|
func NewDB(config DBConfig) (*sql.DB, error) {
|
||
|
|
db, err := sql.Open(config.DriverName, config.DSN)
|
||
|
|
if err != nil {
|
||
|
|
return nil, fmt.Errorf("failed to open database: %w", err)
|
||
|
|
}
|
||
|
|
|
||
|
|
// 配置连接池
|
||
|
|
db.SetMaxOpenConns(config.MaxOpenConns)
|
||
|
|
db.SetMaxIdleConns(config.MaxIdleConns)
|
||
|
|
db.SetConnMaxLifetime(config.ConnMaxLifetime)
|
||
|
|
db.SetConnMaxIdleTime(config.ConnMaxIdleTime)
|
||
|
|
|
||
|
|
// 测试连接
|
||
|
|
if err := db.Ping(); err != nil {
|
||
|
|
db.Close()
|
||
|
|
return nil, fmt.Errorf("failed to ping database: %w", err)
|
||
|
|
}
|
||
|
|
|
||
|
|
return db, nil
|
||
|
|
}
|
||
|
|
|