保持 mongoDB 客户端连接 Golang

尽管有全局范围变量,但我试图理解为什么我的 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 database

var CtxDB, cancel = context.WithTimeout(context.Background(), 10*time.Second)


// DBClient spread all over the application the mongoDB client

var DBClient, err = mongo.NewClient(options.Client().ApplyURI(dbURI))


// DB represent the service database

var DB = DBClient.Database("service-users-data")


// UserCollection represent the user collection

var UserCollection = DB.Collection("users")

这个文件夹结构真的正确吗?

为什么这个客户端不断断开连接?


慕码人2483693
浏览 101回答 2
2回答

FFIVE

延迟调用的参数会立即求值,但直到周围函数返回时才会执行函数调用。当您设置一个defer子句时,它将在定义它的函数结束后执行。基本上,您的延迟数据库关闭是在ConnectToDatabase函数执行后立即发生的。我的建议是您返回sql.DB对象并且仅在应用程序本身终止时才断开连接,也许是在 line 之后s.Shutdown(ctxTimeOut)。

慕容708150

关于客户端断开连接的问题,那是我的错。我正在返回err函数ConnectToDatabase(),我的猜测是停止函数的执行而不是让客户完成他的工作。但是,如果有人有时间检查一下代码和结构,以便给我有关实践的反馈,那将是非常好的,非常感谢 :)
打开App,查看更多内容
随时随地看视频慕课网APP