监控
Overview
In this guide, you can learn how to set up and configure 监控 in the Kotlin Sync driver.
Monitoring is the process of getting information about the activities a running program performs for use in an application or an application performance management library.
You can use the Kotlin Sync driver to monitor cluster, driver command, and connection pool events. These features help you make informed decisions when designing and debugging your application.
This guide shows how to perform the following tasks:
提示
This guide shows how to use information about the meta activity of the driver. To learn how to record data transactions, see the Monitoring Data Changes page.
监控事件
如需监控事件,必须在 MongoClient
实例上注册监听器。
事件是运行程序时发生的任何操作。驱动程序包括监听驱动程序运行时发生的事件子集的功能。
监听器是在某些事件发生时执行某些操作的类。监听器的 API 定义了其可以响应的事件。
Each method of a listener class represents a response to a certain event, and accepts as an argument an event object representing the event.
The Kotlin Sync driver organizes the events it defines into three categories:
命令事件
Server Discovery and Monitoring events
连接池事件
The following sections show how to monitor each event category. For a full list of the events you can monitor, see the Java event package.
命令事件
命令事件是与 MongoDB 数据库命令相关的事件。生成命令事件的数据库命令的一些示例包括 find
、insert
、delete
和 count
。
要监控命令事件,请创建一个实现CommandListener
接口的类,并使用MongoClient
实例。
For more information on MongoDB database commands, see the MongoDB manual entry on database commands in the MongoDB Server manual.
注意
内部命令
The driver does not publish events for commands it calls internally. This
includes database commands the driver uses to monitor your cluster and
commands related to connection establishment, such as the initial hello
command.
例子
This example shows how to make a counter for database commands. The counter keeps track of the number of times the driver successfully executes each database command and prints this information every time a database command finishes.
To make a counter, follow these steps:
创建具有计数器功能的类,实现
CommandListener
接口。Add an instance of the new class to a
MongoClientSettings
object.Configure your
MongoClient
instance with theMongoClientSettings
object.
The following code implements these steps:
import com.mongodb.kotlin.client.MongoClient import org.bson.Document import com.mongodb.event.* import com.mongodb.MongoClientSettings import com.mongodb.ConnectionString class CommandCounter : CommandListener { private val commands = mutableMapOf<String, Int>() override fun commandSucceeded(event: CommandSucceededEvent) { val commandName = event.commandName val count = commands[commandName] ?: 0 commands[commandName] = count + 1 println(commands.toString()) } override fun commandFailed(event: CommandFailedEvent) { println("Failed execution of command '${event.commandName}' with id ${event.requestId}") } } fun main() { val uri = "<connection string uri>" // Instantiate your new listener val commandCounter = CommandCounter() // Include the listener in your client settings val settings = MongoClientSettings.builder() .applyConnectionString(ConnectionString(uri)) .addCommandListener(commandCounter) .build() // Connect to your database val mongoClient = MongoClient.create(settings) val database = mongoClient.getDatabase("sample_mflix") val collection = database.getCollection<Document>("movies") // Run some commands to test the counter collection.find().firstOrNull() collection.find().firstOrNull() mongoClient.close() }
{find=1} {find=2} {find=2, endSessions=1}
For more information on the classes and methods mentioned in this section, see the following API documentation:
服务器发现和监控事件
服务器发现与监控 (SDAM) 事件是指与驱动程序连接到的 MongoDB 实例或集群的状态变化相关的事件。
The driver defines nine SDAM events and provides the following listener interfaces, which listen for three SDAM events each:
ClusterListener : Listens for topology-related events
ServerListener : Listens for events related to
mongod
ormongos
processesServerMonitorListener : Listens for heartbeat-related events
To monitor a type of SDAM event, create a class that implements one of the three
preceding interfaces and register an instance of that class with your
MongoClient
instance.
For a detailed description of each SDAM event, see the MongoDB SDAM monitoring events specification.
例子
This example shows how to make a listener class that prints a message about the write availability of your MongoDB instance.
To make an event that reports write status, perform the following tasks:
Make a class that tracks cluster description changes, and implements the
ClusterListener
interface.Add an instance of the new class to a
MongoClientSettings
object.Configure your
MongoClient
instance with theMongoClientSettings
object.
The following code implements these steps:
import com.mongodb.kotlin.client.MongoClient import org.bson.Document import com.mongodb.event.* import com.mongodb.MongoClientSettings import com.mongodb.ConnectionString class IsWriteable : ClusterListener { private var isWritable = false override fun clusterDescriptionChanged(event: ClusterDescriptionChangedEvent) { if (!isWritable) { if (event.newDescription.hasWritableServer()) { isWritable = true println("Able to write to cluster") } } else { if (!event.newDescription.hasWritableServer()) { isWritable = false println("Unable to write to cluster") } } } } fun main() { val uri = "<connection string uri>" // Instantiate your new listener val clusterListener = IsWriteable() // Include the listener in your client settings val settings = MongoClientSettings.builder() .applyConnectionString(ConnectionString(uri)) .applyToClusterSettings { builder -> builder.addClusterListener(clusterListener) } .build() // Connect to your database val mongoClient = MongoClient.create(settings) val database = mongoClient.getDatabase("sample_mflix") val collection = database.getCollection<Document>("movies") // Run a command to trigger a ClusterDescriptionChangedEvent event collection.find().firstOrNull() mongoClient.close() }
Able to write to server
For more information on the classes and methods mentioned in this section, see the following API documentation:
连接池事件
A connection pool event is an event related to a connection pool held by the driver. A connection pool is a set of open TCP connections your driver maintains with a MongoDB instance. Connection pools help reduce the number of network handshakes your application performs with a MongoDB instance and can help your application run faster.
To monitor connection pool events, create a class that implements the
ConnectionPoolListener
interface and register an instance of that class with your
MongoClient
instance.
例子
This example shows how to make a listener class that prints a message each time you check out a connection from your connection pool.
To make an event that reports connection checkouts, perform the following tasks:
Make a class that tracks checkouts and implements the
CommandListener
interface.Add an instance of the new class to a
MongoClientSettings
object.Configure your
MongoClient
instance with theMongoClientSettings
object.
The following code implements these steps:
import com.mongodb.kotlin.client.MongoClient import org.bson.Document import com.mongodb.event.* import com.mongodb.MongoClientSettings import com.mongodb.ConnectionString class ConnectionPoolLibrarian : ConnectionPoolListener { override fun connectionCheckedOut(event: ConnectionCheckedOutEvent) { println("Let me get you the connection with id ${event.connectionId.localValue}...") } override fun connectionCheckOutFailed(event: ConnectionCheckOutFailedEvent) { println("Something went wrong! Failed to checkout connection.") } } fun main() { val uri = "<connection string uri>" // Instantiate your new listener val cpListener = ConnectionPoolLibrarian() // Include the listener in your client settings val settings = MongoClientSettings.builder() .applyConnectionString(ConnectionString(uri)) .applyToConnectionPoolSettings({ it.addConnectionPoolListener(cpListener) }) .build() // Connect to your database val mongoClient = MongoClient.create(settings) val database = mongoClient.getDatabase("sample_mflix") val collection = database.getCollection<Document>("movies") // Run some commands to test the counter collection.find().firstOrNull() mongoClient.close() }
Let me get you the connection with id 21...
For more information on the classes and methods mentioned in this section, see the following API documentation:
用 JMX 监控连接池事件
您可以使用“Java 管理扩展”(JMX) 监控连接池事件。JMX 提供了监控应用程序和设备的工具。
For more information on JMX, see the official Oracle JMX documentation.
JMX 支持
要启用 JMX 连接池监控,请将 JMXConnectionPoolListener
类的实例添加到 MongoClient
对象。
JMXConnectionPoolListener
类执行以下操作:
Creates MXBean instances for each
mongod
ormongos
process the driver maintains a connection pool with.Registers these MXBean instances with the platform MBean server.
在平台 MBean 服务器上注册的 MXBean 具有以下属性:
属性 | 说明 |
---|---|
| 客户端生成的唯一标识符。当应用程序有多个 |
| 运行 |
|
|
| 连接池的最小大小,包括空闲和正在使用的连接。 |
| 连接池的最大大小,包括空闲连接和使用中的连接。 |
| 连接池的当前大小,包括空闲连接和使用中的连接。 |
| 当前正在使用的连接数。 |
此驱动程序创建的所有 MXBean 实例均位于 "org.mongodb.driver"
域中。
For more information on the topics discussed in this subsection, see the following resources from Oracle:
JMX 和 JConsole 示例
This example shows how you can monitor the driver's connection pools using JMX and JConsole. JConsole is a JMX compliant GUI monitoring tool that comes with the Java Platform.
提示
查阅官方 JMX 与 JConsole 文档
此示例中对 JMX 和 JConsole 的描述只是说明性的,而不是事实来源。 有关保证的最新信息,请查阅以下Oracle官方资源:
以下代码段将 JMXConnectionPoolListener
添加到 MongoClient
实例。然后代码暂停执行,以便您可以导航到 JConsole 并检查连接池。
import com.mongodb.kotlin.client.MongoClient import org.bson.Document import com.mongodb.MongoClientSettings import com.mongodb.ConnectionString import com.mongodb.management.JMXConnectionPoolListener fun main() { val uri = "<connection string uri>" // Instantiate your JMX listener val connectionPoolListener = JMXConnectionPoolListener() // Include the listener in your client settings val settings = MongoClientSettings.builder() .applyConnectionString(ConnectionString(uri)) .applyToConnectionPoolSettings { it.addConnectionPoolListener(connectionPoolListener) } .build() try { // Connect to your database val mongoClient = MongoClient.create(settings) val database = mongoClient.getDatabase("sample_mflix") val collection = database.getCollection<Document>("movies") collection.find().firstOrNull() collection.find().firstOrNull() println("Navigate to JConsole to see your connection pools...") // Pause execution Thread.sleep(Long.MAX_VALUE) mongoClient.close() } catch (e: Exception) { e.printStackTrace() } }
Navigate to JConsole to see your connection pools...
Once you have started your server, open JConsole in your terminal by using the following command:
jconsole
打开 JConsole 后,在图形界面中执行以下操作:
Select the process running the preceding example code.
Press Insecure Connection in the warning dialog box.
单击 MBeans 标签页。
检查
"org.mongodb.driver"
域下的连接池事件。
When you no longer want to inspect your connection pools in JConsole, do the following:
关闭 JConsole窗口以退出 JConsole。
Stop the program running by the preceding code snippet.
For more information on JMX and JConsole, see the following resources from Oracle:
For more information on the JMXConnectionPoolListener
class, see
the API documentation for
JMXConnectionPoolListener.
将驱动程序包含在分布式跟踪系统中
如果使用分布式跟踪系统,则可以包含驱动程序的事件数据。分布式跟踪系统是种应用程序,可在请求传播到面向服务架构中的不同服务时对其进行跟踪。
If you use the driver in a Spring Cloud application, use Spring Cloud Sleuth to include MongoDB event data in the Zipkin distributed tracing system.
If you do not use Spring Cloud or want to include driver event data in a distributed tracing system other than Zipkin, you must write a command event listener that manages spans for your desired distributed tracing system.
提示
To learn more about the concepts discussed in this section, review the following resources:
- Spring Cloud
- TraceMongoCommandListener
- : An implementation of an event listen than manages spans
Dapper : A detailed description of a distributed tracing system from Google Research