为了账号安全,请及时绑定邮箱和手机立即绑定

保持 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 关注
  • 97 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信