AWS Lambda - 无法连接到 SQL Server RDS [英] AWS Lambda - Unable to connect to SQL Server RDS
问题描述
我遇到了与 这篇文章 但是没有提供已发布的答案(没有示例代码),所以我将开始一个新线程并询问你们.
Hi I was having the same problem as this post but the posted answer (no sample code) wasn't provided so I will start a new thread and ask you guys.
我为我们的 lambda 函数创建了一个 AWS 无服务器应用程序 (.Net Core) 项目,下面的代码是我用来在 AWS RDS 中连接的代码.
I have created a AWS Serverless Application (.Net Core) project for our lambda function and below code is what I used to connect in AWS RDS.
string ConnectionString = "Data Source=rds4abc1190.asdfqwerqb9l.us-east-1.rds.amazonaws.com,2855;Initial Catalog=MyDatabase;Persist Security Info=True;User ID=myID;Password=mypassword;Encrypt=False";
using (var Conn = new SqlConnection(ConnectionString))
{
using (var Cmd = new SqlCommand("SELECT * from Customer", Conn))
{
Conn.Open(); //<-- this is where the error fires.
SqlDataReader rdr = Cmd.ExecuteReader();
while (rdr.Read())
{
myDbItems.Add(rdr[1].ToString());
}
Conn.Close();
}
}
<小时>
在本地机器上运行时使用上述代码可以正常工作,但如果部署在 AWS Api Gateway 中,该代码会出错.
Using the above code works fine when running on local machine but if deployed in AWS Api Gateway, that code would error.
"errorType": "SqlException", "errorMessage": "Connection Timeout Expired.在登录后阶段超时时间已过.连接可能在等待服务器完成登录过程并响应时超时;或者它可能在尝试创建多个活动连接时超时.尝试连接到此服务器所花费的持续时间是 - [登录前]初始化=781;握手=1957;[登录]初始化=40;身份验证=122;[登录后] complete=12219;",
"errorType": "SqlException", "errorMessage": "Connection Timeout Expired. The timeout period elapsed during the post-login phase. The connection could have timed out while waiting for server to complete the login process and respond; Or it could have timed out while attempting to create multiple active connections. The duration spent while attempting to connect to this server was - [Pre-Login] initialization=781; handshake=1957; [Login] initialization=40; authentication=122; [Post-Login] complete=12219;",
推荐答案
在 serverless.template 的每个函数中添加了以下内容.
Added the following in each function in the serverless.template.
"Role": "arn:aws:iam::053984854873:role/1234-Dev",
"Policies": [ "AWSLambdaBasicExecutionRole", "AWSLambdaBasicExecutionRole-ABC1234","LambdaAccess-1234" ],
"VpcConfig" : {
"SecurityGroupIds" : ["sg-4f2cbff1","sg-3584a444"],
"SubnetIds" : ["subnet-f2520727","subnet-388b4ab2"]
}
这篇关于AWS Lambda - 无法连接到 SQL Server RDS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!