第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何正確斷開 MongoDB 客戶端

如何正確斷開 MongoDB 客戶端

Go
長風秋雁 2022-07-11 16:26:58
據(jù)我了解,您必須在使用完 MongoDB 后斷開與它的連接,但我不完全確定如何正確操作var collection *mongo.Collectionvar 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}有注釋掉的函數(shù)調用 defer client.Disconnect(ctx) ,如果所有代碼都發(fā)生在 main() 函數(shù)中,這將正常工作,但由于在 init() 執(zhí)行后立即調用 defer,因此 main() 函數(shù)中的 DB 已經斷開連接。所以問題是——處理這個案子的正確方法是什么?
查看完整描述

2 回答

?
拉莫斯之舞

TA貢獻1820條經驗 獲得超10個贊

您的應用程序需要在所有服務或存儲庫中連接 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()

}

在您的存儲庫或服務中,您現(xiàn)在可以輕松獲得 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

}


查看完整回答
反對 回復 2022-07-11
?
開心每一天1111

TA貢獻1836條經驗 獲得超13個贊

在 Python 中執(zhí)行此操作的最佳方法是將數(shù)據(jù)庫連接編寫為單例,然后使用“atexit”模塊來裝飾斷開連接的函數(shù)。這確保了連接只被實例化一次,因為我們不想打開多個連接,因為我們想要共享一個連接,并且在程序結束時連接斷開。


import atexit

from pymongo import MongoClient


class MongoDB:

'''define class attributes'''

__instance = None


@staticmethod

def getInstance():

    """ Static access method. """

    # if the instance doesnt exist envoke the constructor

    if MongoDB.__instance == None:

        MongoDB()

    # return instance

    return MongoDB.__instance


def __init__(self) -> None:

    """ Virtually private constructor. """

    if MongoDB.__instance != None:

        raise Exception("Singleton cannot be instantiated more than once")


    else:

        print("Creating MongoDB connection")

        # set instance and instance attributes

        self.client = MongoClient(config.CONNECTION_STRING)

        MongoDB.__instance = self



@staticmethod

@atexit.register

def closeConnection():

    ''' 

    Python '__del__' aka destructor dunder doesnt always get called

    mainly when program is terminated by ctrl-c so this method is decorated

    by 'atexit' which ensures this method is called upon program termination

    '''

    if MongoDB.__instance != None:

        MongoDB.__instance.client.close()

        print("Closing Connections")

如果有人知道更好的設計模式,請隨時發(fā)表評論,這只是我想出的似乎效果很好的東西。


查看完整回答
反對 回復 2022-07-11
  • 2 回答
  • 0 關注
  • 189 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號