且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Spring Data MongoDB无法关闭MongoDB连接

更新时间:2023-09-13 09:05:04

MongoClient维护一个连接池,您一次使用MongoClient打开一个Db连接,并在您的应用程序中重复使用它,因为建立新的TCP连接在时间和内存上都是昂贵的明智的做法是重复使用连接的原因.另外,新的连接也会导致使用Db上的内存在MongoDB上创建新的线程.

The MongoClient maintains a connection pool,You open a Db connection once with MongoClient and reuse it across your application because setting up a new TCP connection is EXPENSIVE timewise and memory wise that's why you reuse connections. Also a new connection will cause a new Thread to be created on MongoDB using memory on the Db as well.

    要注意的一点是,connectToMongo方法中存在竞争条件.您需要同步对该方法的访问,以确保最多创建一个MongoClient实例.
  • point to be noted that there is a race condition in the connectToMongo method. You need to synchronize access to that method to ensure that at most one instance of MongoClient is ever created.