直接回答:连接字符串的关键是用户名密码、地址端口、库名和时区参数;连接池则用 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()
// SetMaxIdleConns 设置空闲连接池中连接的最大数量
sqlDB.SetMaxIdleConns(10)

// SetMaxOpenConns 设置打开数据库连接的最大数量。
sqlDB.SetMaxOpenConns(10)

// SetConnMaxLifetime 设置了连接可复用的最大时间。
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
//dsn := "root:Rlx2022!@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
PrepareStmt: true, //缓存预编译语句
DisableForeignKeyConstraintWhenMigrating: true, // 禁用外键约束
})

//db, err := gorm.Open(sqlite.Open("./test.sqlite"), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
db.AutoMigrate(new(OneData))
sqlDB, _ := db.DB()
// SetMaxIdleConns 设置空闲连接池中连接的最大数量
sqlDB.SetMaxIdleConns(10)

// SetMaxOpenConns 设置打开数据库连接的最大数量。
sqlDB.SetMaxOpenConns(10)

// SetConnMaxLifetime 设置了连接可复用的最大时间。
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 {

// rds, err := redis.Dial("tcp", "127.0.0.1:6379")
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 Bucket = "IOT"
//var Org = "example.com"
//var token = "替换成你自己的 InfluxDB Token"

// Store the URL of your InfluxDB instance
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
}
}

这篇笔记整理自我自己的实践记录,如果做法有出入,或者你踩过别的坑,欢迎到留言板一起聊聊。

站内搜索

没有找到内容!