-
Notifications
You must be signed in to change notification settings - Fork 0
/
client_db_mysql.go
87 lines (74 loc) · 2.9 KB
/
client_db_mysql.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
79
80
81
82
83
84
85
86
87
package injectors
import (
"time"
kitexGorm "github.com/weedge/craftsman/cloudwego/kitex-contrib/gorm"
"github.com/weedge/craftsman/cloudwego/payment/pkg/utils/logutils"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
type MysqlDBClientOptions struct {
Name string `mapstructure:"name"`
DbEngine string `mapstructure:"dbEngine"`
DSN string `mapstructure:"dsn"`
MaxIdleConns int `mapstructure:"maxIdleConns"`
MaxOpenConns int `mapstructure:"maxOpenConns"`
ConnMaxLifeTime time.Duration `mapstructure:"connMaxLifeTime"`
SlowSqlTimeThreshold time.Duration `mapstructure:"slowSqlTimeThreshold"`
TraceLogLevel logutils.Level `mapstructure:"traceLogLevel"`
}
func DefaultMysqlDBClientOptions() *MysqlDBClientOptions {
return &MysqlDBClientOptions{
Name: "default",
DbEngine: "mysql-innodb",
DSN: "",
MaxIdleConns: 10,
MaxOpenConns: 1000,
ConnMaxLifeTime: 3600 * time.Second,
SlowSqlTimeThreshold: 200 * time.Millisecond,
TraceLogLevel: logutils.LevelTrace,
}
}
func InitMysqlDBClient(opts *MysqlDBClientOptions, kvLogger kitexGorm.IkvLogger) (dbClient *gorm.DB, err error) {
conf := &gorm.Config{
SkipDefaultTransaction: false,
NamingStrategy: nil,
FullSaveAssociations: false,
//Logger: logger.Default.LogMode(logger.Info),
Logger: kitexGorm.NewGormLogger(
kitexGorm.WithKvLogger(kvLogger),
kitexGorm.WithSlowThreshold(opts.SlowSqlTimeThreshold),
kitexGorm.WithTraceLogLevel(opts.TraceLogLevel.KitexLogLevel()),
),
NowFunc: func() time.Time {
return time.Now().Local()
},
DryRun: false,
PrepareStmt: false,
DisableAutomaticPing: false,
DisableForeignKeyConstraintWhenMigrating: false,
DisableNestedTransaction: false,
AllowGlobalUpdate: false,
QueryFields: false,
CreateBatchSize: 0,
ClauseBuilders: map[string]clause.ClauseBuilder{},
ConnPool: nil,
Dialector: nil,
Plugins: map[string]gorm.Plugin{},
}
dbClient, err = gorm.Open(mysql.Open(opts.DSN), conf)
if err != nil {
return
}
sqlDB, err := dbClient.DB()
if err != nil {
return
}
// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
sqlDB.SetMaxIdleConns(opts.MaxIdleConns)
// SetMaxOpenConns sets the maximum number of open connections to the database.
sqlDB.SetMaxOpenConns(opts.MaxOpenConns)
// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
sqlDB.SetConnMaxLifetime(opts.ConnMaxLifeTime)
return
}