英文:
Is mongodb client driver concurrent safe?
问题
在下面的代码中,从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")
Goroutine 2同时使用collection1
和collection2
进行读写操作:
collection2 := client.Database("testing").Collection("collectiontwo")
client
在多个goroutine中使用是否是并发安全的?
英文:
In the below code from codebase, mongodb client is created(as shown below):
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"))
In our scenario:
Goroutine 1 uses collection1
for read & write operations:
collection1 := client.Database("testing").Collection("collectionone")
Go-routine 2 uses both collection1
&collection2
for read & write operations:
collection2 := client.Database("testing").Collection("collectiontwo")
Is client
concurrent safe to be used in multiple go-routines?
答案1
得分: 5
mongo.Database
的文档明确说明:
> Database 是一个 MongoDB 数据库的句柄。它可以被多个 goroutine 并发使用。
而 mongo.Client
则是:
> Client 是一个表示与 MongoDB 部署连接池的句柄。它可以被多个 goroutine 并发使用。
mongo.Collection
也是如此:
> Collection 是一个 MongoDB 集合的句柄。它可以被多个 goroutine 并发使用。
参考链接:https://stackoverflow.com/questions/67862292/goroutine-create-multiple-mongodb-connection/67862482#67862482
英文:
The documentation of mongo.Database
explicitly states that:
> Database is a handle to a MongoDB database. It is safe for concurrent use by multiple goroutines.
And mongo.Client
that:
> Client is a handle representing a pool of connections to a MongoDB deployment. It is safe for concurrent use by multiple goroutines.
And mongo.Collection
:
> Collection is a handle to a MongoDB collection. It is safe for concurrent use by multiple goroutines.
See related: https://stackoverflow.com/questions/67862292/goroutine-create-multiple-mongodb-connection/67862482#67862482
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论