chore: initial import
This commit is contained in:
47
internal/database/database.go
Normal file
47
internal/database/database.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/company/ai-ops/internal/config"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// Pool 是全局数据库连接池
|
||||
var Pool *pgxpool.Pool
|
||||
|
||||
// Init 初始化数据库连接
|
||||
func Init(cfg config.DatabaseConfig) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
poolConfig, err := pgxpool.ParseConfig(cfg.DSN())
|
||||
if err != nil {
|
||||
return fmt.Errorf("parse db config: %w", err)
|
||||
}
|
||||
|
||||
poolConfig.MaxConns = int32(cfg.PoolSize)
|
||||
poolConfig.MinConns = 2
|
||||
poolConfig.MaxConnLifetime = 30 * time.Minute
|
||||
poolConfig.MaxConnIdleTime = 10 * time.Minute
|
||||
|
||||
Pool, err = pgxpool.NewWithConfig(ctx, poolConfig)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create db pool: %w", err)
|
||||
}
|
||||
|
||||
if err := Pool.Ping(ctx); err != nil {
|
||||
return fmt.Errorf("ping db: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close 关闭数据库连接
|
||||
func Close() {
|
||||
if Pool != nil {
|
||||
Pool.Close()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user