30 lines
848 B
Go
30 lines
848 B
Go
package utils_mongo
|
|
|
|
import (
|
|
"context"
|
|
"time"
|
|
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
)
|
|
|
|
type ClientStruct struct {
|
|
Uri string
|
|
MaxPoolSize uint64
|
|
MinPoolSize uint64
|
|
MaxConnIdleTime time.Duration
|
|
ConnectTimeout time.Duration
|
|
SocketTimeout time.Duration
|
|
}
|
|
|
|
func NewMongoClient(ctx context.Context, config *ClientStruct) (*mongo.Client, error) {
|
|
clientOptions := options.Client().ApplyURI(config.Uri).
|
|
SetMaxPoolSize(config.MaxPoolSize). // 最大连接数
|
|
SetMinPoolSize(config.MinPoolSize). // 最小连接数
|
|
SetMaxConnIdleTime(config.MaxConnIdleTime). // 连接最大空闲时间
|
|
SetConnectTimeout(config.ConnectTimeout). // 连接超时
|
|
SetSocketTimeout(config.ConnectTimeout) // 操作超时
|
|
|
|
return mongo.Connect(ctx, clientOptions)
|
|
}
|