Node.js 6.2.0 版本,mongodb-native 2.1.20 版本。程序不会崩溃,卡在数据库查询位置。
自己实现数据库连接部分代码如下:
// 程序启动时调用数据库连接
mongoConnect.connect(config.mongodb.master.url, function (err, db) {
if (err) {
console.log(err);
process.exit(1);
} else {
app.listen(config.server.port, function () {
console.log('apps server start at: ' + config.server.port);
});
module.exports = app;
}
});
// 连接数据库
'use strict';
var MongoClient = require('mongodb').MongoClient;
var mongo = {
'_db': null,
'_mongodbUrl': null,
'_connectOptions': {
'server':{
'auto_reconnect': true,
'poolSize': 10,
'socketOptions':{
'keepAlive': 1
}
},
'db': {
'numberOfRetries': 10,
'retryMiliSeconds': 1000
}
},
connect(mongodbUrl, callback) {
var that = this;
if (!mongodbUrl) {
reject(new Error('missing parameter "mongodbUrl"'));
} else {
that._mongodbUrl = mongodbUrl;
MongoClient.connect(that._mongodbUrl, that._connectOptions, function (err, db) {
if (err) {
console.log(err);
that._db = null;
callback(err);
} else {
db.on('close', function () {
console.log('mongodb server closed');
that._db = null;
});
db.on('timeout', function () {
console.log('mongodb server timeout');
that._db = null;
});
db.on('error', function () {
console.log('mongodb server closed');
that._db = null;
});
that._db = db;
callback(null, that._db);
}
});
}
},
getInstance(callback) {
var that = this;
if (!that._db) {
console.log('reconnect to mongodb');
that.connect(that._mongodbUrl, (err, db) => {
if (err) {
callback(err);
} else {
callback(null, db);
}
});
} else {
console.log('use exists mongodb instance');
callback(null, that._db);
}
}
};
module.exports = mongo;
// 使用数据库
mongo.getInstance(function (err, db) {
var collection = db.collection('users');
collection.find({}).limit(10).toArray(function (err, users) {
if (err) {
res.send(err);
} else {
res.send(users);
}
});
});
出错后,尝试了 Does mongoDB have reconnect issues or am i doing it wrong? 下的所有解决方法,依旧无解。
现在使用 generic-pool
做数据库连接部分,断线频率降低,但是还是会出现断线状况,这时只有重启服务才能解决。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
认证高级PHP讲师