개요
이 가이드 에서는 코틀린 동기 (Kotlin Sync) 운전자 에서 모니터링 설정하다 하고 구성하는 방법을 학습 수 있습니다.
모니터링이란 실행 중인 프로그램이 애플리케이션 혹은 애플리케이션 성능 관리 라이브러리에서 사용하는 데 수행하는 작업에 대한 정보를 가져오는 프로세스입니다.
코틀린 동기 (Kotlin Sync) 운전자 사용하여 클러스터, 운전자 명령 및 연결 풀 이벤트를 모니터 할 수 있습니다. 이러한 기능은 애플리케이션 설계하고 디버깅할 때 정보에 입각한 결정을 내리는 데 도움이 됩니다.
이 가이드 다음 작업을 수행하는 방법을 보여줍니다.
팁
이 가이드 운전자 의 메타 활동에 대한 정보를 사용하는 방법을 보여 줍니다. 데이터 트랜잭션을 기록 방법을 학습하려면 데이터 변경 모니터링 페이지를 참조하세요.
이벤트를 모니터링합니다.
이벤트를 모니터링하려면 MongoClient
인스턴스에 리스너를 등록해야 합니다.
이벤트란 실행 중인 프로그램에서 발생하는 작업 모두를 지칭합니다. 드라이버에는 드라이버가 실행 중일 때 발생하는 이벤트의 하위 집합을 수신하는 기능 등이 있습니다.
리스너란 특정 이벤트가 발생했을 때 어떤 작업을 수행하는 클래스를 말합니다. 리스너의 API는 응답할 수 있는 이벤트를 정의합니다.
리스너 클래스의 각 메서드는 특정 이벤트 에 대한 응답을 나타내며, 이벤트 나타내는 이벤트 객체 인수로 받습니다.
코틀린 동기 (Kotlin Sync) 운전자 이벤트를 세 가지 카테고리로 정의합니다.
명령 이벤트
서버 검색 및 이벤트 모니터링하기
연결 풀 이벤트
다음 섹션에서는 각 이벤트 범주를 모니터 방법을 보여 줍니다. 모니터 할 수 있는 이벤트의 전체 목록은 Java 이벤트 패키지참조하세요.
명령 이벤트
명령 이벤트는 MongoDB 데이터베이스 명령어와 관련된 이벤트입니다. 명령 이벤트를 생성하는 데이터베이스 명령어의 몇 가지 예에는 find
, insert
, delete
, count
등이 있습니다.
명령 이벤트를 모니터 하려면 CommandListener
인터페이스를 구현하는 클래스를 만들고 해당 클래스의 인스턴스 를 MongoClient
인스턴스 에 등록합니다.
MongoDB database 명령에 대한 자세한 내용은 MongoDB Server 매뉴얼의 데이터베이스 명령에 대한 MongoDB 매뉴얼 항목 을 참조하세요.
참고
내부 명령어
운전자 내부적으로 호출하는 명령에 대한 이벤트를 게시하지 않습니다. 여기에는 운전자 클러스터 모니터 데 사용하는 데이터베이스 명령과 초기 hello
명령과 같은 연결 설정과 관련된 명령이 포함됩니다.
중요
수정된 출력
보안 조치로 드라이버는 일부 명령 이벤트의 내용을 수정합니다. 이렇게 하면 이러한 명령 이벤트에 포함된 민감한 정보를 보호할 수 있습니다. 수정된 명령 이벤트의 전체 목록은 MongoDB 명령 로깅 및 모니터링 사양을 참조하세요.
예시
이 예시 데이터베이스 명령에 대한 카운터를 만드는 방법을 보여 줍니다. 카운터는 운전자 각 데이터베이스 명령 성공적으로 실행한 횟수를 추적 하고 데이터베이스 명령 완료될 때마다 이 정보를 인쇄합니다.
카운터를 만들려면 다음 단계를 따르세요.
인터페이스를 구현하는 카운터 기능이 있는 클래스를 생성합니다.
CommandListener
새 클래스의 인스턴스
MongoClientSettings
객체 에 추가합니다.MongoClientSettings
객체 로MongoClient
인스턴스 구성합니다.
다음 코드는 이러한 단계를 구현합니다.
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}
이 섹션에 언급된 클래스 및 메서드에 대한 자세한 내용은 다음 API 설명서를 참조하세요.
서버 검색 및 이벤트 모니터링하기
서버 검색 및 모니터링(SDAM) 이벤트란 드라이버를 연결한 MongoDB 인스턴스 혹은 클러스터의 상태 변경과 관련된 이벤트를 말합니다.
운전자 9개의 SDAM 이벤트를 정의하고 각각 3개의 SDAM 이벤트를 수신하는 다음과 같은 리스너 인터페이스를 제공합니다.
ClusterListener : 토폴로지 관련 이벤트를 수신 대기합니다.
ServerListener :
mongod
또는mongos
프로세스와 관련된 이벤트를 수신 대기합니다.ServerMonitorListener : 하트비트 관련 이벤트를 수신 대기합니다.
SDAM 이벤트 유형을 모니터 하려면 앞의 세 가지 인터페이스 중 하나를 구현하는 클래스를 만들고 해당 클래스의 인스턴스 MongoClient
인스턴스 에 등록합니다.
각 SDAM 이벤트에 대한 자세한 설명은 MongoDB SDAM 모니터링 이벤트 사양을 참조하세요.
예시
이 예시 MongoDB 인스턴스 의 쓰기 (write) 가용성에 대한 메시지를 출력하는 리스너 클래스를 만드는 방법을 보여줍니다.
쓰기 (write) 상태를 보고하는 이벤트 만들려면 다음 작업을 수행하세요.
클러스터 설명 변경 사항을 추적하고
ClusterListener
인터페이스를 구현하는 클래스를 만듭니다.새 클래스의 인스턴스
MongoClientSettings
객체 에 추가합니다.MongoClientSettings
객체 로MongoClient
인스턴스 구성합니다.
다음 코드는 이러한 단계를 구현합니다.
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
이 섹션에 언급된 클래스 및 메서드에 대한 자세한 내용은 다음 API 설명서를 참조하세요.
연결 풀 이벤트
연결 풀 이벤트는 운전자가 보유한 연결 풀 과 관련된 이벤트입니다. 연결 풀 운전자 MongoDB 인스턴스 사용하여 유지 관리하는 개방형 TCP 연결의 설정하다 입니다. 연결 풀은 애플리케이션 MongoDB 인스턴스 로 수행하는 네트워크 핸드셰이크 횟수를 줄이고 애플리케이션 더 빠르게 실행 도움이 될 수 있습니다.
연결 풀 이벤트를 모니터 하려면 ConnectionPoolListener
인터페이스를 구현하는 클래스를 만들고 해당 클래스의 인스턴스 MongoClient
인스턴스 에 등록합니다.
예시
이 예시에서는 연결 풀에서 연결을 체크아웃할 때마다 메시지를 인쇄하는 리스너 클래스를 생성하는 방법을 설명합니다.
연결 체크아웃을 보고하는 이벤트 만들려면 다음 작업을 수행하세요.
결제를 추적하고
CommandListener
인터페이스를 구현하는 클래스를 만듭니다.새 클래스의 인스턴스
MongoClientSettings
객체 에 추가합니다.MongoClientSettings
객체 로MongoClient
인스턴스 구성합니다.
다음 코드는 이러한 단계를 구현합니다.
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...
이 섹션에 언급된 클래스 및 메서드에 대한 자세한 내용은 다음 API 설명서를 참조하세요.
JMX로 연결 풀 이벤트를 모니터링합니다.
Java Management Extensions (JMX) 사용하여 연결 풀 이벤트를 모니터링할 수 있습니다. JMX는 툴을 제공하여 애플리케이션과 기기를 모니터링합니다.
JMX에 대한 자세한 내용 은 공식 Oracle JMX 설명서를 참조하세요.
JMX 지원
JMX 연결 풀 모니터링을 활성화하려면 JMXConnectionPoolListener
클래스의 인스턴스를 MongoClient
객체에 추가합니다.
JMXConnectionPoolListener
클래스는 다음과 같은 작업을 수행합니다.
드라이버가 연결 풀을 유지 관리하는 각
mongod
혹은mongos
프로세스에 대해 MXBean 인스턴스를 생성합니다.이러한 MXBean 인스턴스를 플랫폼 MBean 서버에 등록합니다.
플랫폼 MBean 서버에 등록된 MXBean은 다음과 같은 속성이 있습니다.
속성 | 설명 |
---|---|
| 클라이언트에서 생성한 고유 식별자 식별자는 애플리케이션에 동일한 MongoDB deployment에 연결된 |
|
|
|
|
| 유휴 연결 및 사용 중인 연결 등 연결 풀의 최소 크기 |
| 유휴 연결 및 사용 중인 연결 등 연결 풀의 최대 크기 |
| 유휴 연결 및 사용 중인 연결 등 연결 풀의 현재 크기 |
| 사용 중인 연결의 현재 개수 |
드라이버로 생성된 MXBean 인스턴스는 모두 "org.mongodb.driver"
도메인 아래에 있습니다.
이러한 하위 섹션에서 논의된 주제에 대한 자세한 내용은 Oracle의 다음 리소스를 참조합니다.
JMX 및 JConsole 예시
이 예에서는 JMX 및 JConsole을 사용하여 드라이버의 연결 풀을 모니터링할 수 있는 방법을 보여줍니다. JConsole은 Java 플랫폼과 함께 제공되는 JMX 호환 GUI 모니터링 도구입니다.
팁
공식 JMX 및 JConsole 문서를 참조하세요.
이 예시 의 JMX 및 JConsole에 대한 설명은 사실에 근거한 것이 아니라 예시입니다. 최신 정보를 확인하려면 다음 공식 Oracle 리소스를 참조하세요.
다음 코드 스니펫은 MongoClient
인스턴스에 JMXConnectionPoolListener
를 추가합니다. 그런 다음 코드는 실행을 일시 중지하므로 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...
서버 시작한 후 다음 명령을 사용하여 터미널에서 JConsole을 엽니다.
jconsole
JConsole이 열리면 GUI에서 다음 작업을 수행합니다.
앞의 예제 코드를 실행하는 프로세스를 선택합니다.
경고 대화 상자에서 Insecure Connection을 누릅니다.
MBeans 탭을 클릭합니다.
"org.mongodb.driver"
도메인에서 연결 풀 이벤트를 검사합니다.
JConsole에서 연결 풀을 더 이상 검사하지 않으려면 다음을 수행합니다.
JConsole 창 을 닫아 JConsole을 종료합니다.
앞의 코드 스니펫으로 실행 프로그램을 중지합니다.
JMX 및 JConsole에 대한 자세한 내용은 Oracle에서 제공하는 다음 리소스를 참조하세요.
JMXConnectionPoolListener
클래스에 대한 자세한 내용은 JMXConnectionPoolListener.에 대한 API 설명서를 참조하세요.
분산 추적 시스템에 드라이버를 포함합니다.
분산 추적 시스템을 사용하는 경우 드라이버의 이벤트 데이터를 포함할 수 있습니다. 분산 추적 시스템은 서비스 지향 아키텍처에서 여러 서비스에 걸쳐 전달되는 요청을 추적하는 애플리케이션입니다.
Spring Cloud 애플리케이션 에서 운전자 사용하는 경우, Spring Cloud Sleuth를 사용하여 Zipkin 분산된 추적 시스템에 MongoDB 이벤트 데이터를 포함할 수 있습니다.
Spring Cloud를 사용하지 않거나 Zipkin 이외의 분산된 추적 시스템에 운전자 이벤트 데이터를 포함하려면 원하는 분산된 추적 시스템의 범위 를 관리하는 명령 이벤트 리스너를 쓰기 (write) 해야 합니다.
팁
이 섹션에서 설명하는 개념에 대해 자세히 학습 다음 리소스를 검토 .
- Spring Cloud
- TraceMongoCommandListener
- : 스팬을 관리하는 이벤트 수신의 구현 .
Dapper : Google Research의 분산된 추적 시스템에 대한 자세한 설명입니다.