-
Notifications
You must be signed in to change notification settings - Fork 0
/
connect.go
78 lines (67 loc) · 2.43 KB
/
connect.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package ormx
import (
"context"
"fmt"
"time"
"github.com/cloudfly/flagx"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
"github.com/rs/zerolog"
)
var (
databaseDsn = flagx.NewString("database.dsn", "", "the dsn address of the master database which ormx connect to write")
databaseDsnRead = flagx.NewString("database.dsn.read", "", "the dsn address of the slave database which ormx connect to read")
dbDriver = flagx.NewString("database.driver", "mysql", "the sql driver for executing query")
lifetime = flagx.NewDuration("database.conn.lifetime", "10m", "the maximum amount of seconds a connection may be reused")
idletime = flagx.NewDuration("database.conn.idletime", "1m", "the maximum amount of seconds a connection may be idle")
maxOpen = flagx.NewInt("database.conn.maxopen", 100, "the maximum number of connections to the database server")
maxIdle = flagx.NewInt("database.conn.maxidle", 32, "the maximum number of connections in idle connection poll")
)
var (
db *sqlx.DB
rdb *sqlx.DB
)
// Connect to the database server by using the addr and password specified in flags
func Connect(ctx context.Context) error {
if *databaseDsn == "" {
return nil
}
var (
err error
)
zerolog.Ctx(ctx).Info().Str("dsn", *databaseDsn).Msg("Connecting to master database server")
db, err = sqlx.ConnectContext(ctx, *dbDriver, *databaseDsn)
if err != nil {
return fmt.Errorf("connect error: %w", err)
}
db.SetConnMaxLifetime(time.Duration(lifetime.Msecs) * time.Millisecond)
db.SetConnMaxIdleTime(time.Duration(idletime.Msecs) * time.Millisecond)
db.SetMaxIdleConns(*maxIdle)
db.SetMaxOpenConns(*maxOpen)
if *databaseDsnRead == "" {
zerolog.Ctx(ctx).Info().Str("dsn", *databaseDsnRead).Msg("Connecting to slave database server")
rdb, err = sqlx.ConnectContext(ctx, *dbDriver, *databaseDsnRead)
if err != nil {
return fmt.Errorf("connect error: %w", err)
}
rdb.SetConnMaxLifetime(time.Duration(lifetime.Msecs) * time.Millisecond)
rdb.SetConnMaxIdleTime(time.Duration(idletime.Msecs) * time.Millisecond)
rdb.SetMaxIdleConns(*maxIdle)
rdb.SetMaxOpenConns(*maxOpen)
}
return nil
}
// DefaultProvider return the sqlx.DB created by Connect()
func DefaultProvider(isMaster bool) *sqlx.DB {
if !isMaster && rdb != nil {
return rdb
}
return db
}
// Close the connections to the database server in driver
func Close() error {
if db != nil {
return db.Close()
}
return nil
}