我正在使用node-mongodb-native驱动程序和MongoDB编写一个网站。
我有关于如何管理连接的几个问题:
在所有请求中只使用一个MongoDB连接是否足够?这样做会有性能问题吗?如果可以,我可以设置一个全局连接来在整个应用程序中使用吗?
如果不行,当请求到达时开启新连接然后在处理完请求后关闭它是否好?打开和关闭连接是否昂贵?
应该使用全局连接池吗?我听说这个驱动程序已经具备原生连接池了。这是一个好选择吗?
如果我使用连接池,需要使用多少个连接?
还有其他需要注意的事项吗?
我正在使用node-mongodb-native驱动程序和MongoDB编写一个网站。
我有关于如何管理连接的几个问题:
在所有请求中只使用一个MongoDB连接是否足够?这样做会有性能问题吗?如果可以,我可以设置一个全局连接来在整个应用程序中使用吗?
如果不行,当请求到达时开启新连接然后在处理完请求后关闭它是否好?打开和关闭连接是否昂贵?
应该使用全局连接池吗?我听说这个驱动程序已经具备原生连接池了。这是一个好选择吗?
如果我使用连接池,需要使用多少个连接?
还有其他需要注意的事项吗?
MongoClient
返回的数据库名称和连接对象,并在需要联系数据库时重用该连接。
在您的 Server.js
中定义 var global.dbconnections = [];
创建一个名为 connectionService.js
的服务。它将有两个方法 getConnection
和 createConnection
。
因此,当用户调用 getConnection()
时,它将在全局连接变量中查找详细信息,如果已存在,则返回连接详细信息,否则将调用 createConnection()
并返回连接详细信息。
使用<db_name>
调用此服务,如果它已经存在,则返回连接对象,否则将创建新连接并将其返回给您。
connectionService.js
代码:var mongo = require('mongoskin');
var mongodb = require('mongodb');
var Q = require('q');
var service = {};
service.getConnection = getConnection ;
module.exports = service;
function getConnection(appDB){
var deferred = Q.defer();
var connectionDetails=global.dbconnections.find(item=>item.appDB==appDB)
if(connectionDetails){deferred.resolve(connectionDetails.connection);
}else{createConnection(appDB).then(function(connectionDetails){
deferred.resolve(connectionDetails);})
}
return deferred.promise;
}
function createConnection(appDB){
var deferred = Q.defer();
mongodb.MongoClient.connect(connectionServer + appDB, (err,database)=>
{
if(err) deferred.reject(err.name + ': ' + err.message);
global.dbconnections.push({appDB: appDB, connection: database});
deferred.resolve(database);
})
return deferred.promise;
}
npm i express mongoose
mongodb.js
const express = require('express');
const mongoose =require('mongoose')
const app = express();
mongoose.set('strictQuery', true);
mongoose.connect('mongodb://localhost:27017/db_name', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log('MongoDB Connected...'))
.catch((err) => console.log(err))
app.listen(3000,()=>{ console.log("Started on port 3000 !!!") })
node mongodb.js
var mongoose = require('mongoose');
//Set up default mongoose connection
const bankDB = ()=>{
return mongoose.createConnection('mongodb+srv://<username>:<passwprd>@mydemo.jk4nr.mongodb.net/<database>?retryWrites=true&w=majority',options);
}
bankDB().then(()=>console.log('Connected to mongoDB-Atlas bankApp...'))
.catch((err)=>console.error('Could not connected to mongoDB',err));
//Set up second mongoose connection
const myDB = ()=>{
return mongoose.createConnection('mongodb+srv://<username>:<password>@mydemo.jk4nr.mongodb.net/<database>?retryWrites=true&w=majority',options);
}
myDB().then(()=>console.log('Connected to mongoDB-Atlas connection 2...'))
.catch((err)=>console.error('Could not connected to mongoDB',err));
module.exports = { bankDB(), myDB() };