mongodb客户端驱动并发安全吗?

问题描述 投票:0回答:2

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
并发安全吗?

database mongodb go goroutine mongo-go
2个回答
6
投票

mongo.Database
的文档明确指出:

Database 是 MongoDB 数据库的句柄。 多个 goroutine 并发使用是安全的。

还有

mongo.Client

Client 是一个句柄,代表 MongoDB 部署的连接池。 多个 goroutine 并发使用是安全的。

mongo.Collection

Collection 是 MongoDB 集合的句柄。 多个 goroutine 并发使用是安全的。

参见相关:goroutine创建多个mongodb连接


0
投票

根据 mongoDB 文档 - 游标不是 goroutine 安全的。不要同时在多个 goroutine 中使用同一个游标。

© www.soinside.com 2019 - 2024. All rights reserved.