duidui_fiber/pkg/database/mysql.go
2026-03-27 10:34:03 +08:00

72 lines
1.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package database
import (
"context"
"fmt"
"time"
"dd_fiber_api/config"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
// MySQLClient MySQL客户端封装使用sqlx
type MySQLClient struct {
DB *sqlx.DB
}
// NewMySQLClient 创建MySQL客户端
func NewMySQLClient(cfg *config.MySQLConfig) (*MySQLClient, error) {
if cfg.Database == "" {
return nil, fmt.Errorf("MySQL数据库名不能为空")
}
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 := sqlx.Connect("mysql", dsn)
if err != nil {
return nil, fmt.Errorf("连接MySQL失败: %v", err)
}
// 设置连接池参数
if cfg.MaxOpenConns > 0 {
db.SetMaxOpenConns(cfg.MaxOpenConns)
}
if cfg.MaxIdleConns > 0 {
db.SetMaxIdleConns(cfg.MaxIdleConns)
}
// 解析连接最大生命周期
if cfg.ConnMaxLifetime != "" {
if duration, err := time.ParseDuration(cfg.ConnMaxLifetime); err == nil {
db.SetConnMaxLifetime(duration)
}
}
return &MySQLClient{DB: db}, nil
}
// Close 关闭数据库连接
func (c *MySQLClient) Close() error {
if c.DB != nil {
return c.DB.Close()
}
return nil
}
// Ping 测试数据库连接
func (c *MySQLClient) Ping() error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
return c.DB.PingContext(ctx)
}