40 lines
1010 B
Go
40 lines
1010 B
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
// NewPool создаёт пул соединений с PostgreSQL.
|
|
// Параметры ограничены, чтобы не перегрузить БД.
|
|
func NewPool(ctx context.Context, dsn string, maxConns int32) (*pgxpool.Pool, error) {
|
|
cfg, err := pgxpool.ParseConfig(dsn)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("parse dsn: %w", err)
|
|
}
|
|
|
|
cfg.MaxConns = maxConns
|
|
cfg.MinConns = min(2, maxConns)
|
|
cfg.MaxConnIdleTime = 5 * time.Minute
|
|
cfg.MaxConnLifetime = 30 * time.Minute
|
|
cfg.HealthCheckPeriod = 30 * time.Second
|
|
|
|
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("create pool: %w", err)
|
|
}
|
|
|
|
// Проверяем, что соединение работает.
|
|
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
|
defer cancel()
|
|
if err := pool.Ping(pingCtx); err != nil {
|
|
pool.Close()
|
|
return nil, fmt.Errorf("ping: %w", err)
|
|
}
|
|
|
|
return pool, nil
|
|
}
|