簡體   English   中英

Aws lambda 與 mongoDb 連接

[英]Aws lambda with mongoDb connection

Hello guyz i need an answer to an simple question.I am using Aws lambda with serverless framework and i am using mongoDb connection in aws lambda.I have used connection code inside my handler function and i have used connection pooling.

現在,當我使用 sls deploy 在 AWS 上部署我的應用程序並在部署后,當我第一次調用我的 lambda 時,連接只建立一次,之后在其他 lambda ZDB974238714CA8DE634A7CE1D083A1 上建立連接,而不是創建新連接。很好。

Now after this process i am running a script which is not related with my AWS app to test my concurrent lambda requests.I have called my same lambda API using request npm module in for loop in script and in that case all time my new connnection is創建直到循環終止,而不是使用第一次調用生成的現有循環。有人可以告訴我為什么會發生這種情況以及這背后的原因是什么? 為什么我已經在第一次 lambda 調用上創建了連接時,當此腳本運行時我的連接再次創建。

And same api when i call from postman then it is resuing my connection after first lambda call but when i run this script and from inside script i call this API(using request NPM module) using command "node app.js" then all time till循環終止它創建新的連接。

請幫我解決這個問題。

 'use strict'

 const bodyParser = require('body-parser')
 const express = require('express')
 const serverless = require('serverless-http')
 const cors = require('cors');
 const mongoConnection = require('./connection/mongoDb');
 const app = express()

app.use(cors())
app.use(bodyParser.json())

const handler = serverless(app);
let cachedDb = null;

module.exports.handler = async (event, context) => {
context.callbackWaitsForEmptyEventLoop = false;
if (cachedDb == null) {
let Database = await mongoConnection();
console.log("DB", Database);
cachedDb = Database
}

const baseRouter = require('./routes/index');
app.use('/api', baseRouter);

const result = await handler(event, context);
return result;
};

這是顯示連接參數的 node.js 示例。 也許這會有所幫助?

const express = require("express");
const bodyParser= require("body-parser")
const app = express();
const MongoClient = require("mongodb").MongoClient


MongoClient.connect("mongodb://myusername:mypassword@localhost:27017", (err, client) => {
  if (err) return console.log(err)

  var db = client.db("mydatabase")

  db.collection("mycollection").countDocuments(getCountCallback);

  app.listen(3000, () => {
    console.log("listening on 3000")
  })  
})


function getCountCallback(err, data) {
  console.log(data);
}

app.use(bodyParser.urlencoded({extended: true}))

app.get("/", (req, res) => {
  res.sendFile(__dirname + "/index.html")
})

app.post("/quotes", (req, res) => {
  console.log(req.body)
})

您的示例代碼沒有顯示數據庫服務器的任何主機名,也沒有指定要使用的端口。 請比較您的代碼並與我的示例進行對比。

我看到您在處理程序 scope 之外定義了 cachedDb 變量,以便在重用容器時使其可用。 但是,不能保證容器會被重復使用(請參閱我之前的鏈接),因為 Lambda 的工作方式不是這樣。 如果您多次快速調用相同的函數,Lambda 需要橫向擴展才能快速處理請求。 他們每個人都有自己的容器和連接。

調用完成后,AWS 會將容器保留一段時間(多長時間取決於許多因素,例如 function 大小和 RAM 限制)。 如果您再次調用它,容器可以重用它們的連接。 您可以嘗試以 1 秒的間隔調用 function 20 次,並計算已打開的連接數。 它將低於 20,但高於 1。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM