[英]How to cache or reuse MongoDB database connection in Serverless (AWS Lambda) application
I'm building a Serverless application using NodeJS and using MongoDB .我正在使用NodeJS和MongoDB构建一个无服务器应用程序。 I noticed that a lot of connections are created when handling a request.我注意到在处理请求时会创建很多连接。 So I came up with a caching mechanism but it doesn't seem to be working.所以我想出了一个缓存机制,但它似乎不起作用。 Here is my code.这是我的代码。
Connection file连接文件
'use strict';
const connectDatabase = mongoClient => mongoClient.connect(process.env.MONGODB_STRING, { poolSize: 10 });
const createConnection = (mongoClient, dbConnection) => {
return new Promise(async (resolve, reject) => {
try {
if (dbConnection) {
console.log('===== Cached Connection =====');
resolve(dbConnection);
}
console.log('===== New Connection =====');
let dbPool = await connectDatabase(mongoClient);
resolve(dbPool);
} catch (error) {
reject(error);
}
});
};
const closeDbConnection = conn => {
if (conn) {
return conn.close();
}
};
module.exports = {
connectDatabase: connectDatabase,
createConnection: createConnection,
closeDbConnection: closeDbConnection
};
Handler code处理程序代码
let admin = require('./lib/admin');
let helper = require('./lib/helper');
let connection = require('./lib/connection');
let mongo = require('mongodb');
let mongoClient = mongo.MongoClient;
let cachedDb = null;
let createUser = async (event, context, callback) => {
context.callbackWaitsForEmptyEventLoop = false;
cachedDb = await connection.createConnection(mongoClient, cachedDb);
admin.createUser(cachedDb, helper.parseEvent(event), callback);
};
I'm using a global variable cachedDb
to store the database connection but each and every time I make a request it logs ===== New Connection =====
any idea how to achieve this.我正在使用全局变量cachedDb
来存储数据库连接,但是每次我发出请求时它都会记录===== New Connection =====
任何想法如何实现这一点。 Is there a better way to handle this?.有没有更好的方法来处理这个?
The approach I like using here is a singleton class, like this:我喜欢在这里使用的方法是 singleton class,如下所示:
export default class MyMongoConnection {
static instance;
static getInstance() {
if (!MyMongoConnection.instance) {
MyMongoConnection.instance = MyMongoConnection.createInstance();
}
return MyMongoConnection.instance;
}
static createInstance() {
// Do whatever you need to create the instance
}
}
So you import MyMongoConnection anywhere and just ask for the instance using.getInstance(), if it exists, it reuses it.所以你在任何地方导入 MyMongoConnection 并使用.getInstance() 请求实例,如果它存在,它会重用它。
Hope this helps.希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.