-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexample_mdbPool.go
51 lines (46 loc) · 1.13 KB
/
example_mdbPool.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
// 数据库交互
package Pool
import (
"context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"log"
"sync"
"time"
)
var (
DBPool *MongoPool
once sync.Once
)
func init() {
once.Do(func() {
DBPool = &MongoPool{
pool: make(chan *mongo.Client, 10), //最大闲置连接数
connections: 0, //当前程序连接数
timeout: 10 * time.Second,
uri: "mongodb://user:[email protected]:27017/dbname",
poolSize: 10, //最大连接数 = 当前连接数+闲置连接数
}
})
}
type MongoData struct {
Id string `bson:"id"`
Name string `bson:"name"`
Other string `bson:"other"`
}
func Find() (result MongoData, err error) {
conn, err := DBPool.GetConnection()
if err != nil {
log.Printf("获取数据库连接失败,err=%v", err)
return
}
defer DBPool.CloseConnection(conn)
collection := GetCollection(conn, "testdb", "test")
err = collection.FindOne(context.TODO(), bson.D{{"id", 1}}).Decode(&result)
if err != nil {
log.Printf("查询失败,err=%v", err)
return
}
log.Printf("数据库查询成功,result=%#v", result)
return
}