68 lines
1.2 KiB
Go
68 lines
1.2 KiB
Go
// db/db.go
|
|
package db
|
|
|
|
import (
|
|
"cn/oneao/base-go/conf"
|
|
sqlcg "cn/oneao/base-go/db/sqlc"
|
|
"context"
|
|
"fmt"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
"time"
|
|
)
|
|
|
|
var (
|
|
DB *pgxpool.Pool
|
|
Queries *sqlcg.Queries
|
|
)
|
|
|
|
func InitDB() {
|
|
cfg := conf.GetConf().Pgsql
|
|
|
|
sslMode := "disable"
|
|
if cfg.SllMode {
|
|
sslMode = "require"
|
|
}
|
|
|
|
dsn := fmt.Sprintf(
|
|
"postgres://%s:%s@%s:%d/%s?sslmode=%s&TimeZone=%s",
|
|
cfg.User, cfg.Password, cfg.Host, cfg.Port, cfg.Dbname, sslMode, cfg.TimeZone,
|
|
)
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
|
|
// 使用可修改配置
|
|
cfgPool, err := pgxpool.ParseConfig(dsn)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
// 给连接池参数设置默认值
|
|
if cfg.MaxOpenConns <= 0 {
|
|
cfg.MaxOpenConns = 10
|
|
}
|
|
if cfg.MaxIdleConns <= 0 {
|
|
cfg.MaxIdleConns = 5
|
|
}
|
|
if cfg.ConnMaxLifetime <= 0 {
|
|
cfg.ConnMaxLifetime = 30 * time.Minute
|
|
}
|
|
|
|
cfgPool.MaxConns = cfg.MaxOpenConns
|
|
cfgPool.MinConns = cfg.MaxIdleConns
|
|
cfgPool.MaxConnLifetime = cfg.ConnMaxLifetime
|
|
|
|
pool, err := pgxpool.NewWithConfig(ctx, cfgPool)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
// 测试连接
|
|
if err := pool.Ping(ctx); err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
DB = pool
|
|
Queries = sqlcg.New(DB)
|
|
}
|