Spring data mongodb not closing mongodb connections

若如初见. 提交于 2019-11-29 07:26:28

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.

  • 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.

Spring won't close the connection automatically. Only when context is closed, it will close the connections.

Have a look at this article.

It is better for you to configure mongo options as per this article

But you have to fine tune these values depending on your application traffic.

<beans>

  <mongo:mongo host="localhost" port="27017">
    <mongo:options connections-per-host="8"
                   threads-allowed-to-block-for-connection-multiplier="4"
                   connect-timeout="1000"
                   max-wait-time="1500}"
                   auto-connect-retry="true"
                   socket-keep-alive="true"
                   socket-timeout="1500"
                   slave-ok="true"
                   write-number="1"
                   write-timeout="0"
                   write-fsync="true"/>
  </mongo:mongo/>

</beans>

I've also faced the same issue because of using new instead of autowiring, if you're manually doing so, close connections using

 mongoDBObject.getDB().getMongo().close().

Spring-data-mongodb uses connection pooling to reuse the connection, So it wont closes the connection, and reuse it next time. For this you need to create singleton instance of mongo class.

It works fine if you are creating instance of Mono-repository using Spring IOC (using @AutoWired) Cause it returns singleton instance so only few connections at a time. But i was not creating repository instance using @Autowired i was creating them manually by new method, So it was giving me new mongo() instance each time. new mongo instance means new connection to db. And there was no way to close that. Thats why i was having too many opene connections.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!