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

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

如何在 Golang 中跨包管理 MongoDB 客戶端

如何在 Golang 中跨包管理 MongoDB 客戶端

Go
浮云間 2022-06-13 10:29:42
我目前從MongoDBon開始GoLang。我目前的用例是這樣的。我希望MongoDB Database在特定包中初始化與 my 的連接,并client在其他幾個(gè)本地包中使用返回的連接。這是我嘗試過的,我已經(jīng)將連接初始化到MongoDB一個(gè)名為dataLayer如下的包內(nèi)package dataLayerimport (    "context"    "log"    "time"    "go.mongodb.org/mongo-driver/mongo"    "go.mongodb.org/mongo-driver/mongo/options"    "go.mongodb.org/mongo-driver/mongo/readpref")func InitDataLayer() {    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)    defer cancel()    client, err := mongo.Connect(ctx, options.Client().ApplyURI(credentials.MONGO_DB_ATLAS_URI))    if err != nil {        log.Fatal(err)    } else {        log.Println("Connected to Database")    }}現(xiàn)在,如果我希望client在其他包中使用返回的內(nèi)容,繼續(xù)initDataLayer一遍又一遍地調(diào)用以取回 a是否生產(chǎn)安全client?
查看完整描述

1 回答

?
慕哥6287543

TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超10個(gè)贊

您不必InitDataLayer一遍又一遍地打電話。您只需要?jiǎng)?chuàng)建一個(gè)客戶端,就可以使用同一個(gè)客戶端從不同的地方連接到 Mongo DB。


Mongo 客戶端在內(nèi)部維護(hù)一個(gè)連接池,因此您不必一次又一次地創(chuàng)建此客戶端。


將此客戶端存儲(chǔ)為結(jié)構(gòu)字段并繼續(xù)重復(fù)使用它是一個(gè)很好的設(shè)計(jì)。


編輯:


創(chuàng)建連接


package dataLayer


import (

    "context"

    "log"

    "time"


    "go.mongodb.org/mongo-driver/mongo"

    "go.mongodb.org/mongo-driver/mongo/options"

    "go.mongodb.org/mongo-driver/mongo/readpref"

)


func InitDataLayer()(*mongo.Client) {

    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)

    defer cancel()

    client, err := mongo.Connect(ctx, options.Client().ApplyURI(credentials.MONGO_DB_ATLAS_URI))

    if err != nil {

        log.Fatal(err)

    } else {

        log.Println("Connected to Database")

    }

    return client

}

main.go,


在使用結(jié)束時(shí)關(guān)閉連接,否則會(huì)泄漏連接。


func main(){

   //...

   client = dataLayer.InitDataLayer()

   defer client.Disconnect(context.Background())

   ...

}

Repository/DAL,將客戶端存儲(chǔ)在 Repository 結(jié)構(gòu)中


界面


type BookRepository interface {

   FindById( ctx context.Context, id int) (*Book, error)

}

將客戶端存儲(chǔ)在結(jié)構(gòu)中的存儲(chǔ)庫實(shí)現(xiàn)


type bookRepository struct {

  client *mongo.Client

}


func (r *bookRepository) FindById( ctx context.Context, id int) (*Book, error) {

  var book  Book

  err := r.client.DefaultDatabase().Collection("books").FindOne(ctx, bson.M{"_id": id }).Decode(&book)

  

  if err == mongo.ErrNoDocuments {

    return nil, nil

  }

  if err != nil  {

     return nil, err

  }

  return &book, nil

}


查看完整回答
反對(duì) 回復(fù) 2022-06-13
  • 1 回答
  • 0 關(guān)注
  • 107 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)