Java 我需要明确关闭连接吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19938153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 21:40:38  来源:igfitidea点击:

Do I need to explicitly close connection?

javamongodb

提问by danieln

I'm holding one instance of MongoClientand DBin my application, and every time that I want to execute some operation I call getCollection().
I'm wondering if I need to explicitly close the connection, just like connection.close()in JDBC.

我手里拿的一个实例MongoClient,并DB说我要执行一些操作我电话,每次我的应用程序,和getCollection()
我想知道是否需要明确关闭连接,就像connection.close()在 JDBC 中一样。

To emphasize, I have only one MongoClientinstance. My question is not about closing MongoClientbut closing the connections I believe it opens when I'm calling getCollection().

为了强调,我只有一个MongoClient实例。我的问题不是关闭MongoClient而是关闭连接我相信它会在我打电话时打开getCollection()

采纳答案by Asya Kamsky

No, you do not need to close connections to DB - your only connection is via MongoClient and as the documentation states - it handles connection pooling for you.

不,您不需要关闭与 DB 的连接 - 您唯一的连接是通过 MongoClient 并且如文档所述 - 它为您处理连接池。

The only resource that you would want to clean up would be a cursorwhich you should close()when you're done with it.

您想要清理的唯一资源是一个游标,当您完成它时您应该close()

回答by MariuszS

You should close if you have many MongoClient.

如果你有很多 MongoClient,你应该关闭。

The MongoClient instance actually represents a pool of connections to the database; you will only need one instance of class MongoClient even with multiple threads.

MongoClient.close() to clean up resources

MongoClient.close() - closes the underlying connector, which in turn closes all open connections. Once called, this Mongo instance can no longer be used.

MongoClient 实例实际上代表了一个到数据库的连接池;即使有多个线程,您也只需要 MongoClient 类的一个实例。

MongoClient.close() 清理资源

MongoClient.close() - 关闭底层连接器,进而关闭所有打开的连接。一旦被调用,这个 Mongo 实例就不能再使用了。

More: http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/

更多:http: //docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/