AWS Lambda函数首次运行但不是第二次运行

时间:2017-04-13 04:51:48

标签: c# mysql amazon-web-services aws-lambda

我有一个C#Lambda函数可以在第一次执行时运行但在第二次执行时失败。 我创建了一些日志来帮助我解决问题所在,但我正在努力弄清楚实际发生了什么。

首次执行日志:

START RequestId: XXXXXXXXXXXXXXXXXXXXXXXXXXXXX Version: $LATEST

 1. Connecion to Database is Open
 2. Running Query: SELECT * FROM Employee3
 3. Returning Results
 4. Close connection
 5. Close reader
 6. Dispose cmd
 7. Configure encoding and string to stream
END RequestId: XXXXXXXXXXXXXXXXXXXXXXXX
REPORT RequestId: XXXXXXXXXXXXXXXXXXXXXXXX  Duration: 10097.73 ms   Billed Duration: 10100 ms   Memory Size: 128 MB Max Memory Used: 41 MB  

回复:(我知道这不是有效的JSON,我最终的目标是,但这将是我解决的下一个项目

Connecion to Database is Open
Joe
Bob
Mary

第二次执行日志:

    START RequestId: XXXXXXXXXXXXXXXXXXXXXXXXXXXXX Version: $LATEST

     1. Connecion to Database is Open
     2. Running Query: SELECT * FROM Employee3
       Connection must be valid and open.: InvalidOperationException
       at MySql.Data.MySqlClient.MySqlCommand.Throw(Exception ex)
       at MySql.Data.MySqlClient.MySqlCommand.CheckState()
       at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
       at LambdaDBTest.Function.returnRows(MySqlConnection connection)
       at LambdaDBTest.Function.FunctionHandler(Stream input, ILambdaContext context)
       at lambda_method(Closure , Stream , Stream , ContextInfo )


    END RequestId: XXXXXXXXXXXXXXXXXXXXXXXX
    REPORT RequestId: XXXXXXXXXXXXXXXXXXXXXXXX  Duration: 1203.12 ms    Billed Duration: 1300 ms    Memory Size: 128 MB Max Memory Used: 47 MB

以下是我正在使用的代码:

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using Amazon.Lambda.Core;
using Amazon.Lambda.Serialization;
using System.Text;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializerAttribute(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]

namespace LambdaDBTest
{
    public class Function
    {
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>

        public Stream FunctionHandler(Stream input, ILambdaContext context)
        {
            var dbCon = DBConnection.Instance();

            dbCon.Server = "AWS-URI";
            dbCon.DatabaseName = "DBNAME";
            dbCon.User = "DBUSER";
            dbCon.Password = "DBPASS";
            string textInput;
            if (dbCon.IsConnect())
            {
                textInput = "Connecion to Database is Open";
                LambdaLogger.Log("\n 1. " + textInput);
                textInput += returnRows(dbCon.Connection);
            }
            else
            {
                textInput = "\n Connecion to Database is NOT Open";
            }
            dbCon.Close();
            LambdaLogger.Log("\n 7. Configure encoding and string to stream\n");
            input = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(textInput));
            return input;
        }

        public static MemoryStream GenerateStreamFromString(string value)
        {
            return new MemoryStream(Encoding.UTF8.GetBytes(value ?? ""));
        }

        static string returnRows(MySqlConnection connection)
        {
            string output = null;
            string query = @"SELECT * FROM Employee3";
            LambdaLogger.Log("\n 2. Running Query: " + query);
            var cmd = new MySqlCommand(query, connection);
            var reader = cmd.ExecuteReader();
            LambdaLogger.Log("\n 3. Returning Results");
            while (reader.Read())
            {
                output += "\n" + (string)reader["Name"];
            }
                LambdaLogger.Log("\n 4. Close connection");
            connection.Close();


                LambdaLogger.Log("\n 5. Close reader");
            reader.Close();

                LambdaLogger.Log("\n 6. Dispose cmd");
            cmd.Dispose();
            return output + "\r";
        }
    }
}

所以代码是非常基础的,并且使用MySql.Data 6.10.1-beta Nu-Get Package for MySQL和AWS Lambda进行了一些剪切和粘贴工作。

我无法理解为什么我在第一次尝试而不是第二次尝试时遇到问题。据我所知,Lambda中没有状态保存。

希望我做一些愚蠢的事情或遗漏一些明显的事情,我很乐意收到通知。如果您需要其他信息,请与我们联系。

已编辑代码:

所以发现修复程序如下所示:

public Stream FunctionHandler(Stream input, ILambdaContext context)
        {
            var dbCon = DBConnection.Instance();

            dbCon.Server = "######.rds.amazonaws.com";
            dbCon.DatabaseName = "#####";
            dbCon.User = "#####";
            dbCon.Password = "######";
            string textInput;
            if (dbCon.IsConnect())
            {
                textInput = "Connecion to Database is Open";
                LambdaLogger.Log("\n 1. " + textInput);
                textInput += returnRows(dbCon.Connection);
            }
            else
            {
                textInput = "\n Connecion to Database is NOT Open";
            }

            //    LambdaLogger.Log("\n 7. Close Database connection");
            //dbCon.Close();
            LambdaLogger.Log("\n 8. Configure encoding and string to stream\n");
            input = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(textInput));
            return input;
        }

        public static MemoryStream GenerateStreamFromString(string value)
        {
            return new MemoryStream(Encoding.UTF8.GetBytes(value ?? ""));
        }

        static string returnRows(MySqlConnection connection)
        {
            string output = null;
            string query = @"SELECT * FROM Employee3";
            LambdaLogger.Log("\n 2. Running Query: " + query);
            var cmd = new MySqlCommand(query, connection);
            var reader = cmd.ExecuteReader();
            LambdaLogger.Log("\n 3. Returning Results");
            while (reader.Read())
            {
                output += "\n" + (string)reader["Name"];
            }

            //    LambdaLogger.Log("\n 4. Close connection");
            //connection.Close();


                LambdaLogger.Log("\n 5. Close reader");
            reader.Close();

            //    LambdaLogger.Log("\n 6. Dispose cmd");
            //cmd.Dispose();
            return output + "\r";
        }

进程reader被Lambda冻结了,所以虽然由于.net MySQL驱动程序的连接池我不需要关闭MySQL连接,但我确实需要调用reader.Close();杀死冷冻过程。谢谢Udo Held:)

1 个答案:

答案 0 :(得分:2)

我有一种怀疑。 代码看起来像每次打开和关闭连接都很好。但是,您的驱动程序可能实际上并未关闭连接,而只是将其返回到池中。 AWS freezes请求之间的实例。因此,如果池中的数据库连接保持打开状态,那么由于您的代码被AWS冻结,它实际上可能会断开连接。

查看.net MySQL driver documentation状态“The Connector/Net supports connection pooling for better performance and scalability with database-intensive applications. This is enabled by default.

您没有提供连接字符串,但您应该尝试禁用添加Pooling=false之类的连接池。您可能还想尝试other options