Add max idle/open params to DB connect

This commit is contained in:
Kailash Nadh 2019-12-05 17:28:22 +05:30
parent 0d8abf9435
commit 6b6dc59067
3 changed files with 25 additions and 9 deletions

View File

@ -68,6 +68,9 @@ password = "listmonk"
database = "listmonk" database = "listmonk"
ssl_mode = "disable" ssl_mode = "disable"
# Maximum active and idle connections to pool.
max_open = 50
max_idle = 10
# SMTP servers. # SMTP servers.
[smtp] [smtp]

11
main.go
View File

@ -227,12 +227,11 @@ func initMediaStore() media.Store {
func main() { func main() {
// Connect to the DB. // Connect to the DB.
db, err := connectDB(ko.String("db.host"), var dbCfg dbConf
ko.Int("db.port"), if err := ko.Unmarshal("db", &dbCfg); err != nil {
ko.String("db.user"), log.Fatalf("error loading db config: %v", err)
ko.String("db.password"), }
ko.String("db.database"), db, err := connectDB(dbCfg)
ko.String("db.ssl_mode"))
if err != nil { if err != nil {
logger.Fatalf("error connecting to DB: %v", err) logger.Fatalf("error connecting to DB: %v", err)
} }

View File

@ -75,14 +75,28 @@ type Queries struct {
// GetStats *sqlx.Stmt `query:"get-stats"` // GetStats *sqlx.Stmt `query:"get-stats"`
} }
// dbConf contains database config required for connecting to a DB.
type dbConf struct {
Host string `koanf:"host"`
Port int `koanf:"port"`
User string `koanf:"user"`
Password string `koanf:"password"`
DBName string `koanf:"database"`
SSLMode string `koanf:"ssl_mode"`
MaxOpen int `koanf:"max_open"`
MaxIdle int `koanf:"max_idle"`
}
// connectDB initializes a database connection. // connectDB initializes a database connection.
func connectDB(host string, port int, user, pwd, dbName string, sslMode string) (*sqlx.DB, error) { func connectDB(c dbConf) (*sqlx.DB, error) {
db, err := sqlx.Connect("postgres", db, err := sqlx.Connect("postgres",
fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=%s", host, port, user, pwd, dbName, sslMode)) fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=%s",
c.Host, c.Port, c.User, c.Password, c.DBName, c.SSLMode))
if err != nil { if err != nil {
return nil, err return nil, err
} }
db.SetMaxOpenConns(c.MaxOpen)
db.SetMaxIdleConns(c.MaxIdle)
return db, nil return db, nil
} }