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
}

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ā)表評論,這只是我想出的似乎效果很好的東西。
- 2 回答
- 0 關注
- 189 瀏覽
添加回答
舉報