Get the number of open connections in mongoDB using java

前端 未结 2 1452
北恋
北恋 2021-01-22 08:14

My program requires a large number of connections to be open (Mongo). I get the error :

Too many connections open, can\'t open anymore

相关标签:
2条回答
  • 2021-01-22 08:50

    You can get connection information by using the db.serverStatus() command. It has a connections subdocument which contains the total/available connections information.

    For more information :

    • Documentation of server status
    • Details of connections block
    0 讨论(0)
  • 2021-01-22 09:01

    Check the number of MongoDB connections using MongoDB Scala driver:

    1. Create a MongoDB client:
    import org.mongodb.scala._
    import scala.collection.JavaConverters._
    import scala.concurrent.Await
    import scala.concurrent.duration._
    import scala.util.{Failure, Success, Try}
    
    // To directly connect to the default server localhost on port 27017
    val mongodbClient: MongoClient = MongoClient()
    
    // Use a Connection String
    val mongodbClient: MongoClient = MongoClient("mongodb://localhost")
    
    // or provide custom MongoClientSettings
    val settings: MongoClientSettings = MongoClientSettings.builder()
        .applyToClusterSettings(b => b.hosts(List(new ServerAddress("localhost")).asJava).
        .build()
    val mongodbClient: MongoClient = MongoClient(settings)
    
    1. Call getNoOfMongodbConnection by passing mongodbClient:
    val result = getNoOfMongodbConnection(mongodbClient)
    
    1. Method to get the number of connections(current, available and total)
    def getNoOfMongodbConnection(mongodbClient: MongoClient) = {
    
        val adminDatabase = mongodbClient.getDatabase("admin")
    
        val serverStatus = adminDatabase.runCommand(Document("serverStatus" -> 1)).toFuture()
    
        Try {
          Await.result(serverStatus, 10 seconds)
    
        } match {
          case Success(x) => {
    
            val connection = x.get("connections")
            logger.info("Number of mongodb connection:--> " + connection)
            connection
          }
          case Failure(ex) => {
            logger.error("Got error while getting the number of Mongodb connection:---> " + ex.printStackTrace())
            None
          }
        }
      }
    
    0 讨论(0)
提交回复
热议问题