亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

保持 mongoDB 客戶端連接 Golang

保持 mongoDB 客戶端連接 Golang

Go
慕碼人2483693 2023-03-07 14:35:23
盡管有全局范圍變量,但我試圖理解為什么我的 mongoDB 客戶端斷開連接。有些東西我不明白。我認為,不知何故,這與功能有關ConnectToDatabase()。如果我嘗試在函數中對數據庫進行一些操作ConnectToDatabase(),它運行良好,但使用另一個包時,它會一直返回Client disconnected錯誤。這里的項目結構:├── 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")這個文件夾結構真的正確嗎?為什么這個客戶端不斷斷開連接?
查看完整描述

2 回答

?
FFIVE

TA貢獻1797條經驗 獲得超6個贊

延遲調用的參數會立即求值,但直到周圍函數返回時才會執行函數調用。

當您設置一個defer子句時,它將在定義它的函數結束后執行。

基本上,您的延遲數據庫關閉是在ConnectToDatabase函數執行后立即發生的。

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


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

TA貢獻1831條經驗 獲得超4個贊

關于客戶端斷開連接的問題,那是我的錯。

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

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


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

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

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

公眾號

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