MongoDB客户端驱动程序是否支持并发安全?

huangapple go评论82阅读模式
英文:

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同时使用collection1collection2进行读写操作:

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

huangapple
  • 本文由 发表于 2022年8月13日 12:43:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/73341656.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定