如何使用Java驱动程序检查MongoDB的活动连接状态

问题描述 投票:2回答:3

我需要在调用REST服务时发布(向Graphite)Mongo数据库实例的'可用活动连接数'状态。我知道我们可以使用db.serverStatus()来了解服务器端连接的详细信息。我希望使用JAVA API在客户端获取“可用的活动连接数”信息。 MongoDB Java驱动程序API文档对此没有多大帮助。

java mongodb connection-pooling
3个回答
5
投票

假设您正在使用3.0.x驱动程序,并在默认端口上连接到localhost:

MongoClient mongoClient = new MongoClient();
MongoDatabase database = mongoClient.getDatabase("admin");
Document serverStatus = database.runCommand(new Document("serverStatus", 1));
Map connections = (Map) serverStatus.get("connections");
Integer current = (Integer) connections.get("current");

0
投票

db.serverStatus()提供有关已创建的连接数和可用连接数的信息。如下所示:

    "connections" : {
    "current" : 3,
    "available" : 2045,
    "totalCreated" : NumberLong(3)
}

您还可以使用db.currentOp(true)来获取正在进行的详细信息。

http://docs.mongodb.org/manual/reference/method/db.currentOp/


0
投票

使用MongoDB Scala驱动程序检查MongoDB连接数:

  1. 创建MongoDB客户端:
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. 通过传递mongodbClient调用getNoOfMongodbConnection:
val result = getNoOfMongodbConnection(mongodbClient)
  1. 获得连接数(当前,可用和总数的方法)
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
      }
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.