在下面来自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例程2使用collection1
和collection2
进行读和写操作:
collection2 := client.Database("testing").Collection("collectiontwo")
型client
并发在多个go例程中使用安全吗?
2条答案
按热度按时间ubof19bj1#
mongo.Database
的文档明确指出:Database是MongoDB数据库的句柄。它可以安全地被多个goroutine并发使用。
mongo.Client
:Client是一个句柄,代表一个连接到MongoDB部署的池。它对于多个goroutine并发使用是安全的。
mongo.Collection
:Collection是一个MongoDB集合的句柄。它可以安全地被多个goroutine并发使用。
相关链接:goroutine创建多个mongodb连接
ecbunoof2#
根据mongoDB文档-游标不是goroutine安全的。不要同时在多个goroutine中使用同一个游标。