몽구스를 통해 간단한 쿼리를 작성하여 MongoDB를 모니터링하기 위해 작은 노드를 작성합니다. 무언가가 반환되면 서비스는 사용 가능한 것으로 간주됩니다. 내 스크립트는 다음과 같습니다Mongoose는 두 번째 요청시 DB에 2 개의 연결을 엽니 다.
var res;
var logPrefix = '[MongoDB]';
var counter = 0;
var mongoose = require('mongoose');
// Simple schema and model for getting a companyprofiles document
var companyProfile = new mongoose.Schema({
_id: String
});
companyProfile.virtual('Id').get(function() {return this._id});
function closeConnection() {
console.log('8');
mongoose.connection.close(function() {
console.log('9');
console.log('%s Closed connection%d', logPrefix, counter);
});
}
function connectAndCheckHealth() {
console.log('2');
mongoose.connect('mongodb://localhost:27017/testdb');
console.log('3');
mongoose.connection.on('error', function(err) {
console.log('%s Error connecting to DB:\n%s %s', logPrefix, logPrefix, err);
res.send(503, 'ERR');
});
mongoose.connection.on('open', function() {
mongoose.connection.db.serverConfig.options.auto_reconnect = false;
});
console.log('4');
mongoose.connection.on('connected', checkHealth);
console.log('5');
mongoose.connection.on('close', function() {
console.log('%s Connection to MongoDB closed %d', logPrefix, counter);
});
}
function checkHealth() {
console.log('6');
cpModel = mongoose.model('companyProfile', companyProfile, 'companyprofiles');
cpModel.findById('spin', handleModelResponse);
}
function handleModelResponse(error, doc) {
console.log('7');
closeConnection();
console.log('10');
if (error !== null) {
console.log('11');
console.log('%s Error handling response from model:\n%s %s', logPrefix, logPrefix, error);
res.send(503, 'ERR');
} else {
console.log('12');
if (doc.Id.match(/company1/)) {
console.log('13');
console.log('%s App status is ok', logPrefix);
res.send(200, 'OK');
} else {
console.log('14');
console.log('%s Couldn\'t find the spin company profile. Found %s', logPrefix, doc.Id);
res.send(503, 'ERR');
}
}
}
module.exports = {
health: function(response) {
counter++;
var date = new Date();
console.log('%s Retrieving health from MongoDB at %s', logPrefix, date);
res = response;
console.log(mongoose.connection);
console.log('1');
connectAndCheckHealth();
console.log('15');
}
}
위에서 볼 수 있듯이, console.log 행에 스크립트를 사용하여 제어 흐름을 시도하고 시도해 보았습니다. 출력은 다음과 같습니다.
1
2
3
4
5
15
6
6
6
7
8
[MongoDB] Connection to MongoDB closed 3
[MongoDB] Connection to MongoDB closed 3
[MongoDB] Connection to MongoDB closed 3
9
[MongoDB] Closed connection3
10
12
13
[MongoDB] App status is ok
7
8
9
[MongoDB] Closed connection3
10
12
13
[MongoDB] App status is ok
/home/GTP/healthcheck/node_modules/mongoose/lib/utils.js:413
throw err;
^
Error: Can't set headers after they are sent.
6이 세 번 표시됩니다 (연결 한 후 콜백). 왜 우리가 여러 연결을 여는 지 말할 수 없습니다. 자동 연결을 해제하고 요청이있을 때마다 연결을 종료합니다.
도움을 주시면 감사하겠습니다.
방금 시도했습니다. 그것은 원래 게시물에 설명 된 것과 동일한 시나리오를 멈추지 않았습니다. – brimble2010
@ brimble2010 이상한. 'connected'' 이벤트에 대해'on' 대신에'once'를 사용해보십시오 :'mongoose.connection.once ('connected', checkHealth);' – JohnnyHK
당신의 답과 주석의 조합이이 문제를 해결했습니다. 감사! – brimble2010