1 回答

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
}
- 1 回答
- 0 關(guān)注
- 107 瀏覽
添加回答
舉報(bào)