在codebase中的以下代码中,创建了mongodb客户端(如下所示):
import (
"context"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
在我们的场景中:
Goroutine 1 使用
collection1
进行读写操作:
collection1 := client.Database("testing").Collection("collectionone")
Go-routine 2 同时使用
collection1
和 collection2
进行读写操作:
collection2 := client.Database("testing").Collection("collectiontwo")
在多个 go 例程中使用
client
并发安全吗?
mongo.Database
的文档明确指出:
Database 是 MongoDB 数据库的句柄。 多个 goroutine 并发使用是安全的。
mongo.Client
:
Client 是一个句柄,代表 MongoDB 部署的连接池。 多个 goroutine 并发使用是安全的。
mongo.Collection
:
Collection 是 MongoDB 集合的句柄。 多个 goroutine 并发使用是安全的。
根据 mongoDB 文档 - 游标不是 goroutine 安全的。不要同时在多个 goroutine 中使用同一个游标。