문서 메뉴

문서 홈애플리케이션 개발MongoDB 드라이버Node.js 드라이버

클러스터 모니터링

이 페이지의 내용

  • 개요
  • 이벤트 구독 예시
  • 이벤트 설명
  • 이벤트 문서 예시
  • serverDescriptionChanged
  • serverHeartbeatStarted
  • serverHeartbeatSucceeded
  • serverHeartbeatFailed
  • serverOpening
  • serverClosed
  • 토폴로지 열기
  • 토폴로지 닫힘
  • 토폴로지 설명 변경됨

이 가이드에서는 MongoDB 인스턴스, 복제본 세트 또는 샤드 cluster에서 토폴로지 이벤트를 모니터링하는 방법을 보여줍니다. 연결한 인스턴스 또는 cluster의 상태가 변경된 경우 드라이버는 SDAM(서버 검색 및 모니터링) 이벤트라고도 하는 토폴로지 이벤트를 생성합니다. 예를 들어, 드라이버는 사용자가 새 연결을 설정하거나 cluster가 새 프라이머리 연결을 선택할 때 이벤트를 생성합니다.

다음 섹션에서는 애플리케이션에서 토폴로지 변경 사항을 기록하고 이러한 이벤트에서 제공된 정보를 탐색하는 방법을 보여 줍니다.

애플리케이션에서 하나 이상의 SDAM 이벤트를 구독하면 드라이버를 사용해 액세스할 수 있습니다. 다음 예제는 복제본 세트에 연결하고 MongoDB 배포에서 생성된 SDAM 이벤트 중 하나를 구독하는 방법을 보여줍니다.

/* Subscribe to SDAM event */
const { MongoClient } = require("mongodb");
// Replace the following with your MongoDB deployment's connection string
const uri = "mongodb+srv://<clusterUrl>/?replicaSet=rs&writeConcern=majority";
const client = new MongoClient(uri);
// Replace <event name> with the name of the event you are subscribing to
const eventName = "<event name>";
// Subscribe to a specified event and print a message when the event is received
client.on(eventName, event => {
console.log(`received ${eventName}: ${JSON.stringify(event, null, 2)}`);
});
async function run() {
try {
// Establish and verify connection to the database
await client.db("admin").command({ ping: 1 });
console.log("Connected successfully");
} finally {
// Close the database connection on completion or error
await client.close();
}
}
run().catch(console.dir);

다음 SDAM 이벤트 중 하나를 구독할 수 있습니다.

이벤트 이름
설명
serverOpening
인스턴스에 대한 연결이 열릴 때 생성됩니다.
serverClosed
인스턴스에 대한 연결이 닫힐 때 생성됩니다.
serverDescriptionChanged
인스턴스 상태가 변경될 때 생성됩니다(예: 세컨더리에서 프라이머리로).
topologyOpening
인스턴스에 연결을 시도하기 전에 생성됩니다.
topologyClosed
토폴로지의 모든 인스턴스 연결이 닫힌 후에 생성됩니다.
topologyDescriptionChanged
새 프라이머리 투표 또는 mongos 프록시 연결이 끊어지는 등 토폴로지가 변경될 때 생성됩니다.
serverHeartbeatStarted
MongoDB 인스턴스에 hello 명령을 실행하기 전에 생성됩니다.
serverHeartbeatSucceeded
hello 명령이 MongoDB 인스턴스에서 성공적으로 반환될 때 생성됩니다.
serverHeartbeatFailed
특정 MongoDB 인스턴스에 대해 실행된 hello 명령이 성공적인 응답을 반환하지 못할 때 생성됩니다.

다음 섹션에서는 각 유형의 SDAM 이벤트에 대한 샘플 출력을 보여줍니다.

ServerDescriptionChangedEvent {
topologyId: 0,
address: 'localhost:27017',
previousDescription: ServerDescription {
address: 'localhost:27017',
error: null,
roundTripTime: 0,
lastUpdateTime: 1571251089030,
lastWriteDate: null,
opTime: null,
type: 'Unknown',
minWireVersion: 0,
maxWireVersion: 0,
hosts: [],
passives: [],
arbiters: [],
tags: []
},
newDescription: ServerDescription {
address: 'localhost:27017',
error: null,
roundTripTime: 0,
lastUpdateTime: 1571251089051,
lastWriteDate: 2019-10-16T18:38:07.000Z,
opTime: { ts: Timestamp, t: 18 },
type: 'RSPrimary',
minWireVersion: 0,
maxWireVersion: 7,
maxBsonObjectSize: 16777216,
maxMessageSizeBytes: 48000000,
maxWriteBatchSize: 100000,
me: 'localhost:27017',
hosts: [ 'localhost:27017' ],
passives: [],
arbiters: [],
tags: [],
setName: 'rs',
setVersion: 1,
electionId: ObjectID,
primary: 'localhost:27017',
logicalSessionTimeoutMinutes: 30,
'$clusterTime': ClusterTime
}
}

이 이벤트에서 ServerDescription 객체의 type 필드에는 다음 가능한 값 중 하나가 포함됩니다.

유형
설명
Unknown
알 수 없는 인스턴스
Standalone
독립형 인스턴스
Mongos
Mongo 프록시 인스턴스
PossiblePrimary
하나 이상의 서버가 이를 프라이머리 서버로 인식하지만, 아직 모든 인스턴스에서 확인되지는 않았습니다.
RSPrimary
프라이머리 인스턴스
RSSecondary
세컨더리 인스턴스
RSArbiter
중재자 인스턴스
RSOther
RSGhost 및 RSOther 사양 참조 자세한 내용은
RSGhost
ServerHeartbeatStartedEvent {
connectionId: 'localhost:27017'
}
ServerHeartbeatSucceededEvent {
duration: 1.939997,
reply:{
hosts: [ 'localhost:27017' ],
setName: 'rs',
setVersion: 1,
isWritablePrimary: true,
secondary: false,
primary: 'localhost:27017',
me: 'localhost:27017',
electionId: ObjectID,
lastWrite: {
opTime: { ts: [Timestamp], t: 18 },
lastWriteDate: 2019-10-16T18:38:17.000Z,
majorityOpTime: { ts: [Timestamp], t: 18 },
majorityWriteDate: 2019-10-16T18:38:17.000Z
},
maxBsonObjectSize: 16777216,
maxMessageSizeBytes: 48000000,
maxWriteBatchSize: 100000,
localTime: 2019-10-16T18:38:19.589Z,
logicalSessionTimeoutMinutes: 30,
minWireVersion: 0,
maxWireVersion: 7,
readOnly: false,
ok: 1,
operationTime: Timestamp,
'$clusterTime': ClusterTime
},
connectionId: 'localhost:27017'
}
ServerHeartbeatFailed {
duration: 20,
failure: MongoError('some error'),
connectionId: 'localhost:27017'
}
ServerOpeningEvent {
topologyId: 0,
address: 'localhost:27017'
}
ServerClosedEvent {
topologyId: 0,
address: 'localhost:27017'
}
TopologyOpeningEvent {
topologyId: 0
}
TopologyClosedEvent {
topologyId: 0
}
TopologyDescriptionChangedEvent {
topologyId: 0,
previousDescription: TopologyDescription {
type: 'ReplicaSetNoPrimary',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers: Map {
'localhost:27017' => ServerDescription
},
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
options: Object,
error: undefined,
commonWireVersion: null
},
newDescription: TopologyDescription {
type: 'ReplicaSetWithPrimary',
setName: 'rs',
maxSetVersion: 1,
maxElectionId: null,
servers: Map {
'localhost:27017' => ServerDescription
},
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: 30,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
options: Object,
error: undefined,
commonWireVersion: 7
}
}

이 이벤트에서 TopologyDescription 객체의 type 필드에는 다음 가능한 값 중 하나가 포함됩니다.

유형
설명
Single
독립형 인스턴스
ReplicaSetWithPrimary
프라이머리가 있는 복제본 세트
ReplicaSetNoPrimary
프라이머리가 없는 복제본 세트
Sharded
샤딩된 클러스터
Unknown
알 수 없는 토폴로지
← 모니터링