u
This commit is contained in:
1 parent
8408cf779f
commit
25a9e41025
58 files changed
+2079
-6308
No files matched your search
@@ -2,7 +2,7 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"cn/oneao/base-go/config"
|
||||
"cn/oneao/base-go/conf"
|
||||
sqlcg "cn/oneao/base-go/db/sqlc"
|
||||
"context"
|
||||
"fmt"
|
||||
@@ -11,19 +11,18 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
DB *pgxpool.Pool
|
||||
DBClient *sqlcg.Queries
|
||||
DB *pgxpool.Pool
|
||||
Queries *sqlcg.Queries
|
||||
)
|
||||
|
||||
func InitDB() error {
|
||||
cfg := config.Db
|
||||
func InitDB() {
|
||||
cfg := conf.GetConf().Pgsql
|
||||
|
||||
sslMode := "disable"
|
||||
if cfg.SllMode {
|
||||
sslMode = "require"
|
||||
}
|
||||
|
||||
// 构建 DSN
|
||||
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,
|
||||
@@ -32,25 +31,37 @@ func InitDB() error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
pool, err := pgxpool.New(ctx, dsn)
|
||||
// 使用可修改配置
|
||||
cfgPool, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
return fmt.Errorf("unable to connect to database: %w", err)
|
||||
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 {
|
||||
return fmt.Errorf("ping database failed: %w", err)
|
||||
panic(err)
|
||||
}
|
||||
|
||||
DB = pool
|
||||
|
||||
// 初始化 sqlc Queries,全局可用
|
||||
DBClient = sqlcg.New(DB)
|
||||
|
||||
// 可选:设置连接池参数
|
||||
pool.Config().MaxConns = int32(cfg.MaxOpenConns)
|
||||
pool.Config().MinConns = int32(cfg.MaxIdleConns)
|
||||
pool.Config().MaxConnLifetime = cfg.ConnMaxLifetime
|
||||
|
||||
return nil
|
||||
Queries = sqlcg.New(DB)
|
||||
}
|
||||
Reference in new issue
Block a user