101 lines
1.8 KiB
Go
101 lines
1.8 KiB
Go
package boots
|
|
|
|
import (
|
|
"allapp-go/internal/config"
|
|
"context"
|
|
"fmt"
|
|
"net/url"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
func InitPgsql(cfg *config.Config) (*pgxpool.Pool, error) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
|
|
pg := cfg.Postgres
|
|
|
|
// ssl
|
|
sslMode := "disable"
|
|
if pg.SslMode {
|
|
sslMode = "require"
|
|
}
|
|
|
|
// 密码转义
|
|
password := url.QueryEscape(pg.Password)
|
|
|
|
// DSN
|
|
dsn := fmt.Sprintf(
|
|
"postgres://%s:%s@%s:%d/%s?sslmode=%s",
|
|
pg.User,
|
|
password,
|
|
pg.Host,
|
|
pg.Port,
|
|
pg.Dbname,
|
|
sslMode,
|
|
)
|
|
|
|
// 解析配置
|
|
conf, err := pgxpool.ParseConfig(dsn)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// ======================
|
|
// 连接池配置(带默认值)
|
|
// ======================
|
|
|
|
// 默认最大连接数
|
|
maxConns := int32(20)
|
|
if pg.MaxOpenConns > 0 {
|
|
maxConns = int32(pg.MaxOpenConns)
|
|
}
|
|
|
|
// 默认最小连接数
|
|
minConns := int32(2)
|
|
if pg.MaxIdleConns > 0 {
|
|
minConns = int32(pg.MaxIdleConns)
|
|
}
|
|
|
|
// 防止配置错误:min > max
|
|
if minConns > maxConns {
|
|
minConns = maxConns
|
|
}
|
|
|
|
// 应用配置
|
|
conf.MaxConns = maxConns
|
|
conf.MinConns = minConns
|
|
|
|
// 默认连接最大生命周期
|
|
if pg.ConnMaxLifetime > 0 {
|
|
conf.MaxConnLifetime = pg.ConnMaxLifetime
|
|
} else {
|
|
conf.MaxConnLifetime = time.Hour
|
|
}
|
|
|
|
// (推荐补充)空闲连接最大存活时间
|
|
conf.MaxConnIdleTime = 30 * time.Minute
|
|
|
|
// ======================
|
|
// 时区设置(正确方式 ⭐)
|
|
// ======================
|
|
if pg.TimeZone != "" {
|
|
conf.ConnConfig.RuntimeParams["TimeZone"] = pg.TimeZone
|
|
}
|
|
|
|
// 创建连接池
|
|
db, err := pgxpool.NewWithConfig(ctx, conf)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// 测试连接
|
|
if err := db.Ping(ctx); err != nil {
|
|
db.Close()
|
|
return nil, err
|
|
}
|
|
|
|
return db, nil
|
|
}
|