我必须如何/在何处/何时关闭 MongoClient? [英] How/where/when do I must call to MongoClient close?

查看:220
本文介绍了我必须如何/在何处/何时关闭 MongoClient?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Java 开发一个 Web 应用程序,我对关闭 MongoClient 有疑问.

I am developing a web application in java and I have a doubt about closing MongoClient.

看到这个http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/#getting-started-with-java-driver

MongoClient 实例实际上代表了一个连接池数据库;你只需要 MongoClient 类的一个实例即使有多个线程.有关更多信息,请参阅并发文档页面信息.MongoClient 类被设计为线程安全和线程之间共享.通常,您只为一个给定的实例创建 1 个实例数据库集群并在您的应用程序中使用它.如果对于某些您决定创建许多 MongoClient 实例的原因,请注意:所有每个 MongoClient 应用资源使用限制(最大连接数等)实例来处理一个实例,确保你调用MongoClient.close() 清理资源

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. See the concurrency doc page for more information. The MongoClient class is designed to be thread safe and shared among threads. Typically you create only 1 instance for a given database cluster and use it across your application. If for some reason you decide to create many MongoClient instances, note that: all resource usage limits (max connections, etc) apply per MongoClient instance to dispose of an instance, make sure you call MongoClient.close() to clean up resources

还有这个http://docs.mongodb.org/ecosystem/drivers/java-concurrency/#java-driver-concurrency

Java MongoDB 驱动程序是线程安全的.如果您在网络中使用服务环境,例如,您应该创建一个MongoClient 实例,您可以在每个请求中使用它.这MongoClient 对象维护一个内部连接池数据库(默认最大池大小为 100).对于每个请求DB(查找、插入等)Java 线程将从池,执行操作,并释放连接.这表示每次使用的连接(套接字)可能不同.

The Java MongoDB driver is thread safe. If you are using in a web serving environment, for example, you should create a single MongoClient instance, and you can use it in every request. The MongoClient object maintains an internal pool of connections to the database (default maximum pool size of 100). For every request to the DB (find, insert, etc) the Java thread will obtain a connection from the pool, execute the operation, and release the connection. This means the connection (socket) used may be different each time.

看来我必须有一个唯一的 MongoClient 实例.我的疑问是:我必须如何/在何处/何时关闭 MongoClient?

It seems that I must have an only instance of MongoClient. My doubt is: How/where/when do I must call to MongoClient close?

谢谢

推荐答案

API 文档 说:

关闭底层连接器,进而关闭所有打开的连接.一旦调用,此 Mongo 实例将无法再使用."​​

"closes the underlying connector, which in turn closes all open connections. Once called, this Mongo instance can no longer be used. "

因此,我假设您仅在您不想再次打开 MongoDB 连接时(在此运行时期间)才关闭它.换句话说,仅在使用此客户端实例的应用程序生命周期结束时.

So, I would assume, that you only close it when you never want to open a MongoDB connection again (during this runtime). In other words, only at the end of the lifecycle of the application that uses this client instance.

这篇关于我必须如何/在何处/何时关闭 MongoClient?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆