简体   繁体   English

Aws lambda 函数连接到 mongodb

[英]Aws lambda function connect to mongodb

I have a simple lambda function which connects to database and find user.我有一个简单的 lambda 函数,它连接到数据库并查找用户。

import pymongo

def my_handler(event, context):
    client = pymongo.MongoClient('uri') #My db connection here. 
    db = client.dbName
    col = db.users
    col.find_one({'email':'example@gmail.com'})
    foundedUser = col.find_one({'hello':'Amazon DocumentDB'})
    print(foundedUser)
    client.close()

I got a weird problem, sometimes lambda connects and find user like for 100ms or even less.我遇到了一个奇怪的问题,有时 lambda 会连接并找到像这样的用户 100 毫秒或更短时间。 But sometimes there is a timed out error after 30 sec.但有时会在 30 秒后出现超时错误。 I have all vpc configs and so on.我有所有的 vpc 配置等等。 I've tried to make it using node.js and now trying with python result is the same.我已经尝试使用 node.js 来实现它,现在尝试使用 python 结果是一样的。 Any suggestions ?有什么建议 ?

So I was running into the same issue.所以我遇到了同样的问题。 Check these out.检查这些。

https://blog.cloudboost.io/i-wish-i-knew-how-to-use-mongodb-connection-in-aws-lambda-f91cd2694ae5 https://blog.cloudboost.io/i-wish-i-knew-how-to-use-mongodb-connection-in-aws-lambda-f91cd2694ae5

https://www.mongodb.com/blog/post/optimizing-aws-lambda-performance-with-mongodb-atlas-and-nodejs https://www.mongodb.com/blog/post/optimizing-aws-lambda-performance-with-mongodb-atlas-and-nodejs

and this和这个

https://hackernoon.com/building-a-serverless-rest-api-with-node-js-and-mongodb-2e0ed0638f47 https://hackernoon.com/building-a-serverless-rest-api-with-node-js-and-mongodb-2e0ed0638f47

Apparently, AWS Lambda is "stateless" and the way that I understand it, once the function is called on a cold start it runs your code and connects to your database.显然,AWS Lambda 是“无状态的”,按照我的理解,一旦在冷启动时调用该函数,它就会运行您的代码并连接到您的数据库。 After that, any call you make to your Lambda function for a certain time (say 5 minutes) will use that same connection.之后,您在特定时间(例如 5 分钟)内对 Lambda 函数进行的任何调用都将使用相同的连接。 Afterwards, if the connection is closed and a function is invoked again, the Lamda doesn't reestablish a connection to the database.之后,如果连接关闭并再次调用函数,Lamda 不会重新建立与数据库的连接。

The tutorials should hopefully help set it up so that it checks for a connection on each function call.这些教程应该有助于设置它,以便它检查每个函数调用的连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM