直接回答:连接字符串的关键是用户名密码、地址端口、库名和时区参数;连接池则用 SetMaxOpenConns、SetMaxIdleConns、SetConnMaxLifetime 三个方法按业务量调,不设置很容易出现连接数打满。
1. sqlite
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| db, err := gorm.Open(sqlite.Open("./db.sqlite"), &gorm.Config{}) if err != nil { panic("failed to connect database") } db.AutoMigrate(new(EntityModel.Data)) db.AutoMigrate(new(EntityModel.User)) sqlDB, _ := db.DB() sqlDB.SetMaxIdleConns(10)
sqlDB.SetMaxOpenConns(10)
sqlDB.SetConnMaxLifetime(time.Hour) return db
|
2.mysql
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{ PrepareStmt: true, DisableForeignKeyConstraintWhenMigrating: true, })
if err != nil { panic("failed to connect database") } db.AutoMigrate(new(OneData)) sqlDB, _ := db.DB() sqlDB.SetMaxIdleConns(10)
sqlDB.SetMaxOpenConns(10)
sqlDB.SetConnMaxLifetime(time.Hour) DB = db
|
3.redis
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| func init() { flag.Parse() Pool = newPool(*flag.String("redis数据库地址", DB.Confs["redisIP"]+":"+DB.Confs["redisPort"], "")) } func newPool(addr string) *redis.Pool {
return &redis.Pool{ Dial: func() (redis.Conn, error) { c, err := redis.Dial("tcp", addr) if err != nil { return nil, err } return c, nil }, MaxIdle: 16, MaxActive: 0, IdleTimeout: 300, }
}
|
4.InfluxDB
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
| var Bucket = DB.Confs["influxBucket"] var Org = DB.Confs["influxOrg"] var token = DB.Confs["influxToken"]
var url = "http://localhost:8086" var influxConn = initInflux()
func initInflux() influxdb2.Client { client := influxdb2.NewClient(url, token) return client }
func GetInfluxClicen() influxdb2.Client { ping, err := influxConn.Ping(context.Background()) if err != nil { return nil } if ping { return influxConn } else { influxConn = initInflux() return influxConn } }
|
这篇笔记整理自我自己的实践记录,如果做法有出入,或者你踩过别的坑,欢迎到留言板一起聊聊。