如何在 AWS Lambda 上读写二维码

This article was translated from English: Does it need improvement?
Translated
View the article in English
Amazon Lambda Architecture Logo related to 如何在 AWS Lambda 上读写二维码

这篇说明文章提供了使用 IronQR 设置 AWS Lambda 函数的详细指南。 在本教程中,您将了解如何配置 IronQR 以将二维码直接读写到 S3 存储桶。

安装

本文将使用 S3 文件桶,因此 *AWSSDK.S3需要 * 软件包。

立即在您的项目中开始使用IronQR,并享受免费试用。

第一步:
green arrow pointer

创建 AWS Lambda 项目

使用 Visual Studio,创建容器化 AWS Lambda 是一个简单的过程:

添加软件包依赖关系

.NET 8 中的 IronQR 库可在 AWS Lambda 上运行,无需额外依赖。 要配置它,请按下图所示修改项目的 Dockerfile:


FROM public.ecr.aws/lambda/dotnet:8

# 安装必要的软件包

运行 dnf update -y

WORKDIR /var/task

# 该 COPY 命令将 .NET Lambda 项目的构建工件从主机复制到映像中。

# COPY 的来源应与 .NET Lambda 项目发布其构建工件的位置相匹配。

如果正在构建 Lambda 函数

# 使用 AWS .NET Lambda 工具时,"--docker-host-build-output-dir "开关控制 .NET Lambda 项目的位置。

# 将建立。

.NET Lambda 项目模板默认有`--docker-host-build-output-dir`。

# 在 aws-lambda-tools-defaults.json 文件中设置为 "bin/Release/lambda-publish"。

#

# 也可以使用 Docker 多阶段构建来在映像中构建 .NET Lambda 项目。

# 有关此方法的更多信息,请查看项目的 README.md 文件。

复制 "bin/Release/lambda-publish" 。

修改 FunctionHandler 代码

本示例创建一个 QR 代码,将其上传到 S3 存储桶,并读取新生成的 QR 代码。

在 try 块之前,文件路径指定在 IronQrNuget 目录中,并带有一个全局唯一标识符(GUID)作为文件名。 写入 "方法根据提供的值生成 QR 代码,生成的 JPG 字节数组将传递给 "读取 "方法,用于读取 QR 代码。 这表明 AWS Lambda 函数能够读取 QR 代码。

using Amazon.Lambda.Core;
using Amazon.S3;
using Amazon.S3.Model;
using IronQr;

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

namespace IronQrNuGetAwsLambda;

public class Function
{
    private static readonly IAmazonS3 _s3Client = new AmazonS3Client(Amazon.RegionEndpoint.APSoutheast1);

    /// <param name="context">The ILambdaContext that provides methods for logging and describing the Lambda environment.</param>
    /// <returns></returns>
    public async Task FunctionHandler(ILambdaContext context)
    {
        IronQr.License.LicenseKey = "IronQR-MYLICENSE-KEY-1EF01";

        string bucketName = "deploymenttestbucket";
        string objectKey = $"IronQrNuget/{Guid.NewGuid()}.png";

        try
        {
            // Creating a qr is as simple as:
            var myQr = QrWriter.Write("12345");

            context.Logger.LogLine($"QR created.");

            // Upload the JPG to S3
            await UploadJpgToS3Async(bucketName, objectKey, myQr.Save().ExportBytesAsJpg());

            context.Logger.LogLine($"QR uploaded successfully to {bucketName}/{objectKey}");

            // Load the asset into QrImageInput
            QrImageInput imageInput = new QrImageInput(myQr.Save());

            // Create a QR Reader object
            QrReader reader = new QrReader();

            var resultFromByte = reader.Read(imageInput);

            foreach (var item in resultFromByte)
            {
                // Log the read value out
                context.Logger.LogLine($"QR value is = {item.Value}");
            }
        }
        catch (Exception e)
        {
            context.Logger.LogLine($"[ERROR] FunctionHandler: {e.Message}");
        }
    }
    // Function to upload the JPG file to S3
    private async Task UploadJpgToS3Async(string bucketName, string objectKey, byte[] pdfBytes)
    {
        using (var memoryStream = new MemoryStream(pdfBytes))
        {
            var request = new PutObjectRequest
            {
                BucketName = bucketName,
                Key = objectKey,
                InputStream = memoryStream,
                ContentType = "image/jpg",
            };

            await _s3Client.PutObjectAsync(request);
        }
    }
}
using Amazon.Lambda.Core;
using Amazon.S3;
using Amazon.S3.Model;
using IronQr;

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

namespace IronQrNuGetAwsLambda;

public class Function
{
    private static readonly IAmazonS3 _s3Client = new AmazonS3Client(Amazon.RegionEndpoint.APSoutheast1);

    /// <param name="context">The ILambdaContext that provides methods for logging and describing the Lambda environment.</param>
    /// <returns></returns>
    public async Task FunctionHandler(ILambdaContext context)
    {
        IronQr.License.LicenseKey = "IronQR-MYLICENSE-KEY-1EF01";

        string bucketName = "deploymenttestbucket";
        string objectKey = $"IronQrNuget/{Guid.NewGuid()}.png";

        try
        {
            // Creating a qr is as simple as:
            var myQr = QrWriter.Write("12345");

            context.Logger.LogLine($"QR created.");

            // Upload the JPG to S3
            await UploadJpgToS3Async(bucketName, objectKey, myQr.Save().ExportBytesAsJpg());

            context.Logger.LogLine($"QR uploaded successfully to {bucketName}/{objectKey}");

            // Load the asset into QrImageInput
            QrImageInput imageInput = new QrImageInput(myQr.Save());

            // Create a QR Reader object
            QrReader reader = new QrReader();

            var resultFromByte = reader.Read(imageInput);

            foreach (var item in resultFromByte)
            {
                // Log the read value out
                context.Logger.LogLine($"QR value is = {item.Value}");
            }
        }
        catch (Exception e)
        {
            context.Logger.LogLine($"[ERROR] FunctionHandler: {e.Message}");
        }
    }
    // Function to upload the JPG file to S3
    private async Task UploadJpgToS3Async(string bucketName, string objectKey, byte[] pdfBytes)
    {
        using (var memoryStream = new MemoryStream(pdfBytes))
        {
            var request = new PutObjectRequest
            {
                BucketName = bucketName,
                Key = objectKey,
                InputStream = memoryStream,
                ContentType = "image/jpg",
            };

            await _s3Client.PutObjectAsync(request);
        }
    }
}
Imports Amazon.Lambda.Core
Imports Amazon.S3
Imports Amazon.S3.Model
Imports IronQr

' Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
<Assembly: LambdaSerializer(GetType(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))>

Namespace IronQrNuGetAwsLambda

	Public Class [Function]
		Private Shared ReadOnly _s3Client As IAmazonS3 = New AmazonS3Client(Amazon.RegionEndpoint.APSoutheast1)

		''' <param name="context">The ILambdaContext that provides methods for logging and describing the Lambda environment.</param>
		''' <returns></returns>
		Public Async Function FunctionHandler(ByVal context As ILambdaContext) As Task
			IronQr.License.LicenseKey = "IronQR-MYLICENSE-KEY-1EF01"

			Dim bucketName As String = "deploymenttestbucket"
			Dim objectKey As String = $"IronQrNuget/{Guid.NewGuid()}.png"

			Try
				' Creating a qr is as simple as:
				Dim myQr = QrWriter.Write("12345")

				context.Logger.LogLine($"QR created.")

				' Upload the JPG to S3
				Await UploadJpgToS3Async(bucketName, objectKey, myQr.Save().ExportBytesAsJpg())

				context.Logger.LogLine($"QR uploaded successfully to {bucketName}/{objectKey}")

				' Load the asset into QrImageInput
				Dim imageInput As New QrImageInput(myQr.Save())

				' Create a QR Reader object
				Dim reader As New QrReader()

				Dim resultFromByte = reader.Read(imageInput)

				For Each item In resultFromByte
					' Log the read value out
					context.Logger.LogLine($"QR value is = {item.Value}")
				Next item
			Catch e As Exception
				context.Logger.LogLine($"[ERROR] FunctionHandler: {e.Message}")
			End Try
		End Function
		' Function to upload the JPG file to S3
		Private Async Function UploadJpgToS3Async(ByVal bucketName As String, ByVal objectKey As String, ByVal pdfBytes() As Byte) As Task
			Using memoryStream As New MemoryStream(pdfBytes)
				Dim request = New PutObjectRequest With {
					.BucketName = bucketName,
					.Key = objectKey,
					.InputStream = memoryStream,
					.ContentType = "image/jpg"
				}

				Await _s3Client.PutObjectAsync(request)
			End Using
		End Function
	End Class
End Namespace
VB   C#

增加内存和超时

Lambda 函数的内存分配取决于文档的大小和同时处理的数量。 作为起点,在 aws-lambda-tools-defaults.json 中将内存设置为 512 MB,超时时间设置为 300 秒。


"function-memory-size" : 512,

"function-timeout" : 300

如果内存不足,程序会出现错误:"Runtime exited with error: signal: killed"。增加内存大小有助于解决这一问题。 如需进一步指导,请查看故障排除文章:AWS Lambda - 运行时退出信号:已杀死.

出版

要在 Visual Studio 中发布,只需右键单击项目并选择 "发布到 AWS Lambda...然后配置所需的设置。 欲了解更多信息,请访问AWS 网站.

试用!

您可以通过以下方式激活 Lambda 函数:Lambda 控制台或通过 Visual Studio。