如何正确断开MongoDB客户端的连接



据我所知,在使用完MongoDB后,您必须断开与它的连接,但我不完全确定如何正确地进行

var collection *mongo.Collection
var ctx = context.TODO()
func init() {
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017/")
client, err := mongo.Connect(ctx, clientOptions)
if err != nil {
log.Fatal(err)
}
//defer client.Disconnect(ctx)
err = client.Ping(ctx, nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected successfully")
collection = client.Database("testDB").Collection("testCollection") //create DB
}

函数调用已被注释掉defer client.Disconnect(ctx)如果所有代码都发生在main((函数中,这会很好,但由于defer在init((执行后立即被调用,所以main((中的DB已经断开连接。

因此,问题是,处理此案的正确方式是什么?

您的应用程序在所有服务或存储库中都需要连接的MongoDB客户端,因此,如果您在应用程序包中分离了MongoDB客户端连接和断开功能,则会更容易。您不需要连接MongoDB客户端,如果您的服务器正在启动,那么如果您的服务或存储库需要MongoDB客户端连接,您可以先连接。

// db.go
package application
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"log"
"os"
)
var client *mongo.Client
func ResolveClientDB() *mongo.Client {
if client != nil {
return client
}
var err error
// TODO add to your .env.yml or .config.yml MONGODB_URI: mongodb://localhost:27017
clientOptions := options.Client().ApplyURI(os.Getenv("MONGODB_URI"))
client, err = mongo.Connect(context.Background(), clientOptions)
if err != nil {
log.Fatal(err)
}
// check the connection
err = client.Ping(context.Background(), nil)
if err != nil {
log.Fatal(err)
}
// TODO optional you can log your connected MongoDB client
return client
}
func CloseClientDB() {
if client == nil {
return
}
err := client.Disconnect(context.TODO())
if err != nil {
log.Fatal(err)
}
// TODO optional you can log your closed MongoDB client
fmt.Println("Connection to MongoDB closed.")
}

主要:

func main() {
// TODO add your main code here
defer application.CloseClientDB()
}

在您的存储库或服务中,您现在可以轻松获得MongoDB客户端:

// account_repository.go
// TODO add here your account repository interface
func (repository *accountRepository) getClient() *mongo.Client {
if repository.client != nil {
return repository.client
}
repository.client = application.ResolveClientDB()
return repository.client
}
func (repository *accountRepository) FindOneByFilter(filter bson.D) (*model.Account, error) {
var account *model.Account
collection := repository.getClient().Database("yourDB").Collection("account")
err := collection.FindOne(context.Background(), filter).Decode(&account)
return account, err
}

最新更新