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

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

保持 mongoDB 客戶端連接 Golang

保持 mongoDB 客戶端連接 Golang

Go
慕碼人2483693 2023-03-07 14:35:23
盡管有全局范圍變量,但我試圖理解為什么我的 mongoDB 客戶端斷開連接。有些東西我不明白。我認(rèn)為,不知何故,這與功能有關(guān)ConnectToDatabase()。如果我嘗試在函數(shù)中對數(shù)據(jù)庫進(jìn)行一些操作ConnectToDatabase(),它運行良好,但使用另一個包時,它會一直返回Client disconnected錯誤。這里的項目結(jié)構(gòu):├── database│  ├── connect.go│  └── models├── go.mod├── go.sum├── handlers│  └── user.go├── main.go├── README.md└── services   ├── create-user.go   └── get-users.go這里的代碼:func main() {    fmt.Println("Users Data service started")    err := DB.ConnectToDatabase()    if err != nil {        log.Fatal(err)    }    l := log.New(os.Stdout, "service-user-data - ", log.LstdFlags)    userH := handlers.User(l)    sMux := http.NewServeMux()    sMux.Handle("/", userH)    s := &http.Server{        Addr:         ":9090",        Handler:      sMux,        IdleTimeout:  120 * time.Second,        ReadTimeout:  1 * time.Second,        WriteTimeout: 1 * time.Second,    }    go func() {        err := s.ListenAndServe()        if err != nil {            l.Fatal(err)        }    }()    sigChan := make(chan os.Signal)    signal.Notify(sigChan, os.Interrupt)    signal.Notify(sigChan, os.Kill)    // Wait for an available signal    // Then print the message into the channel    sig := <-sigChan    l.Println("Recieved terminated, gracefully shutdown", sig)    ctxTimeOut, cancel := context.WithTimeout(context.Background(), 30*time.Second)    defer cancel()    s.Shutdown(ctxTimeOut)}const (    dbURI = "mongodb://localhost:27017")// CtxDB represent the context fot the databasevar CtxDB, cancel = context.WithTimeout(context.Background(), 10*time.Second)// DBClient spread all over the application the mongoDB clientvar DBClient, err = mongo.NewClient(options.Client().ApplyURI(dbURI))// DB represent the service databasevar DB = DBClient.Database("service-users-data")// UserCollection represent the user collectionvar UserCollection = DB.Collection("users")這個文件夾結(jié)構(gòu)真的正確嗎?為什么這個客戶端不斷斷開連接?
查看完整描述

2 回答

?
FFIVE

TA貢獻(xiàn)1797條經(jīng)驗 獲得超6個贊

延遲調(diào)用的參數(shù)會立即求值,但直到周圍函數(shù)返回時才會執(zhí)行函數(shù)調(diào)用。

當(dāng)您設(shè)置一個defer子句時,它將在定義它的函數(shù)結(jié)束后執(zhí)行。

基本上,您的延遲數(shù)據(jù)庫關(guān)閉是在ConnectToDatabase函數(shù)執(zhí)行后立即發(fā)生的。

我的建議是您返回sql.DB對象并且僅在應(yīng)用程序本身終止時才斷開連接,也許是在 line 之后s.Shutdown(ctxTimeOut)


查看完整回答
反對 回復(fù) 2023-03-07
?
慕容708150

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

關(guān)于客戶端斷開連接的問題,那是我的錯。

我正在返回err函數(shù)ConnectToDatabase(),我的猜測是停止函數(shù)的執(zhí)行而不是讓客戶完成他的工作。

但是,如果有人有時間檢查一下代碼和結(jié)構(gòu),以便給我有關(guān)實踐的反饋,那將是非常好的,非常感謝 :)


查看完整回答
反對 回復(fù) 2023-03-07
  • 2 回答
  • 0 關(guān)注
  • 138 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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