Best way to connect to MongoDB

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

Best way to connect to MongoDB

问题

我的问题是,我应该在所有的处理程序中使用goroutines连接到MongoDB,然后断开连接吗?

还是我应该只在应用程序启动时连接到MongoDB,并保持连接长时间保持活动状态,并在处理程序中使用该连接?

哪种方法最好?

如果您能解释一下优缺点,我将不胜感激。

英文:

My question is that should I connect to MongoDB in all of my handlers using goroutines and then disconnect the connection.

Or I should just connect to MongoDB when app starts and keep connection alive for a long time and use that connection in my handlers.

What is the best approach?

I would be thankful if you explain the advantages and disadvantages.

答案1

得分: 1

后者更好

当应用程序启动时连接到MongoDB,并保持连接长时间,并在处理程序中使用该连接

这样可以避免每次需要与数据库交互时都要连接数据库,并且不必处理与数据库连接不一致的情况,前者可能会导致很多复杂性。

通常情况下,连接到数据库应该只发生一次(可能在您的main.go文件中),然后您可以在项目的其他部分引用该连接。

英文:

The latter is better

> Connect to MongoDB when app starts and keep connection alive for a long time and use that connection in my handlers

it prevents you from having to connect to the database when you need to interact with the database all the time and having to deal with cases where connection to the database is inconsistent, the former might lead to a lot of complexity.

Conventionally, connecting to your db should occur once (probably in your main.go file) and you can reference the connection in other parts of the project.

答案2

得分: 0

我的方法已经被证明非常高效。

首先,定义一个内部数据包,如下所示:

package data

import (
	"context"
	"log"
	"os"
	"time"

	"github.com/joho/godotenv"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func MongoConnect() (*mongo.Client, error) {
	godotenv.Load(".env")
	str := os.Getenv("CONNECTION_STRING")
	client, err := mongo.NewClient(options.Client().ApplyURI(str))
	if err != nil {
		log.Fatal(err)
	}
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	err = client.Connect(ctx)
	if err != nil {
		log.Fatal(err)
	}
	return client, nil
}

func ConnectToCollection(collectionName string) (*mongo.Collection, error) {
	client, err := MongoConnect()
	if err != nil {
		return nil, err
	}
	collection := client.Database("DATABASE_NAME").Collection(collectionName)
	return collection, nil
}

完成后,你可以在每个需要它的端点组(包)中使用ConnectToCollection作为全局变量。例如:

package xxx

import "app_name/whatever/data"

var coll, _ = data.ConnectToCollection("xxx_collection_name")

func myFunction() {
	coll.InsertOne(...)
}

这样就可以在myFunction中使用coll.InsertOne(...)了。

英文:

My approach that has proven to be quite performant.
Define an internal data package like so :

package data

import (
	"context"
	"log"
	"os"
	"time"

	"github.com/joho/godotenv"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func MongoConnect() (*mongo.Client, error) {
	godotenv.Load(".env")
	str := os.Getenv("CONNECTION_STRING")
	client, err := mongo.NewClient(options.Client().ApplyURI(str))
	if err != nil {
		log.Fatal(err)
	}
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	err = client.Connect(ctx)
	if err != nil {
		log.Fatal(err)
	}
	return client, nil
}

func ConnectToCollection(collectionName string) (*mongo.Collection, error) {
	client, err := MongoConnect()
	if err != nil {
		return nil, err
	}
	collection := client.Database("DATABASE_NAME").Collection(collectionName)
	return collection, nil
}

Once this is done, you can basically use this ConnectToCollection in every endpoint group (package) that needs it in a global variable. E.G:

package xxx

import "app_name/whatever/data"

var coll, _ = data.ConnectToCollection("xxx_collection_name")


func myFunction() {
	coll.InsertOne(...)
}

huangapple
  • 本文由 发表于 2021年8月30日 13:07:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/68979136.html
匿名

发表评论

匿名网友

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

确定