创建多个 MongoDB 连接的 goroutine

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

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 还有用于设置 MaxConnIdleTimeMinPoolSize 属性的方法。

但要知道,这并不会加快速度。如果有成千上万个 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(&quot;&lt;your-connection-string&gt;&quot;).
    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.

huangapple
  • 本文由 发表于 2021年6月7日 02:13:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/67862292.html
匿名

发表评论

匿名网友

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

确定