英文:
goroutine create multiple mongodb connection
问题
如何在Golang中管理超过100,000个goroutine的MongoDB连接。
我创建了一个*mongo.Client
实例,然后使用这个相同的客户端,但它创建了多个连接。
英文:
How to manage MongoDB connection for more than 100000 goroutines in golang.
I have created one *mongo.Client
instance then using this same client but it creates multiple connections.
答案1
得分: 5
mongo.Client
管理着一个内部连接池,你不需要担心这个。mongo.Client
可以安全地并发使用。
如果你想限制内部连接池的大小,可以在连接时使用 ClientOptions
。例如:
clientOpts := options.Client().ApplyURI("<your-connection-string>").
SetMaxPoolSize(100) // 最多允许100个连接
client, err := mongo.Connect(context.TODO(), clientOpts)
if err != nil {
log.Fatal(err)
}
引用自 ClientOptions.SetMaxPoolSize()
:
> SetMaxPoolSize 指定了驱动程序连接池对每个服务器允许的最大连接数。当达到这个最大值时,对服务器的请求将被阻塞。也可以通过 "maxPoolSize" URI 选项来设置(例如 "maxPoolSize=100")。默认值为100。如果设置为0,将被设置为 math.MaxInt64。
ClientOptions
还有用于设置 MaxConnIdleTime
和 MinPoolSize
属性的方法。
但要知道,这并不会加快速度。如果有成千上万个 goroutine 与 MongoDB 交互,很可能 MongoDB 将成为瓶颈。
英文:
The mongo.Client
manages an internal connection pool. You do not have to worry about that. mongo.Client
is safe for concurrent use.
If you want to limit the internal pool, you may do so at connection using ClientOptions
. For example:
clientOpts := options.Client().ApplyURI("<your-connection-string>").
SetMaxPoolSize(100) // Allow no more than 100 connections
client, err := mongo.Connect(context.TODO(), clientOpts)
if err != nil {
log.Fatal(err)
}
Quoting from ClientOptions.SetMaxPoolSize()
:
> SetMaxPoolSize specifies that maximum number of connections allowed in the driver's connection pool to each server. Requests to a server will block if this maximum is reached. This can also be set through the "maxPoolSize" URI option (e.g. "maxPoolSize=100"). The default is 100. If this is 0, it will be set to math.MaxInt64.
ClientOptions
also has methods for setting the MaxConnIdleTime
and MinPoolSize
properties.
But know that this won't speed things up. If you have a hundred thousand goroutines all interacting with MongoDB, likely MongoDB will be your bottleneck.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论