u
This commit is contained in:
1 parent
89aaef1d6b
commit
6d54a9e407
192 files changed
+971
-51708
No files matched your search
@@ -1,84 +0,0 @@
|
||||
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
|
||||
}
|
||||
|
||||
// ======================
|
||||
// 连接池配置
|
||||
// ======================
|
||||
|
||||
// 最大连接数
|
||||
if pg.MaxOpenConns > 0 {
|
||||
conf.MaxConns = int32(pg.MaxOpenConns)
|
||||
}
|
||||
|
||||
// 最小连接数(近似 idle)
|
||||
if pg.MaxIdleConns > 0 {
|
||||
conf.MinConns = int32(pg.MaxIdleConns)
|
||||
}
|
||||
|
||||
// 连接最大生命周期
|
||||
if pg.ConnMaxLifetime > 0 {
|
||||
conf.MaxConnLifetime = pg.ConnMaxLifetime
|
||||
}
|
||||
|
||||
// ======================
|
||||
// 时区设置(正确方式 ⭐)
|
||||
// ======================
|
||||
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
|
||||
}
|
||||
Reference in new issue
Block a user