forked from mtusi2026/mtusi2026lab4
ЛР4 - БПИ2303 - Стругов - на 4
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// openPool открывает pgx-пул соединений с ограничениями: без лимита один
|
||||
// зависший клиент/медленный запрос мог бы захватить все соединения Postgres.
|
||||
// pgxpool — "родной" пул для pgx (в отличие от generic database/sql),
|
||||
// с нативной поддержкой PostgreSQL-типов и собственным health-check'ом фона.
|
||||
func openPool(ctx context.Context, dsn string) (*pgxpool.Pool, error) {
|
||||
cfg, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("парсинг DSN: %w", err)
|
||||
}
|
||||
cfg.MaxConns = 20
|
||||
cfg.MinConns = 1
|
||||
cfg.MaxConnLifetime = 30 * time.Minute
|
||||
cfg.MaxConnIdleTime = 5 * time.Minute
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("создание пула: %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
|
||||
}
|
||||
|
||||
// queryTimeout — таймаут на отдельный SQL-запрос: зависший диск/сеть к БД
|
||||
// не должен вешать HTTP-обработчик навечно.
|
||||
const queryTimeout = 3 * time.Second
|
||||
|
||||
func withTimeout(parent context.Context) (context.Context, context.CancelFunc) {
|
||||
return context.WithTimeout(parent, queryTimeout)
|
||||
}
|
||||
Reference in New Issue
Block a user