盡管有全局范圍變量,但我試圖理解為什么我的 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)真的正確嗎?為什么這個客戶端不斷斷開連接?
保持 mongoDB 客戶端連接 Golang
慕碼人2483693
2023-03-07 14:35:23