如何在 AWS Lambda 上读写二维码
这篇说明文章提供了使用 IronQR 设置 AWS Lambda 函数的详细指南。 在本教程中,您将了解如何配置 IronQR 以将二维码直接读写到 S3 存储桶。
How to Read & Write QR Codes on AWS Lambda
安装
本文将使用一个S3桶,因此需要AWSSDK.S3包。
立即在您的项目中开始使用IronQR,并享受免费试用。
创建 AWS Lambda 项目
使用 Visual Studio,创建容器化 AWS Lambda 是一个简单的过程:
- 安装AWS Toolkit for Visual Studio
- 选择“AWS Lambda 项目(.NET Core - C#)”
选择一个“.NET 8(容器镜像)”蓝图,然后选择“完成”。
添加软件包依赖关系
.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) 作为文件名。 Write
方法根据提供的值生成QR码,然后将生成的JPG字节数组传递给Read
方法以读取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);
}
}
}
增加内存和超时
Lambda 函数的内存分配取决于文档的大小和同时处理的数量。 作为起点,将内存设置为512 MB,并在aws-lambda-tools-defaults.json
中将超时设置为300秒。
"function-memory-size" : 512,
"function-timeout" : 300
如果内存不足,程序会出现错误:"Runtime exited with error: signal: killed"。增加内存大小有助于解决这一问题。 如需进一步指导,请查看故障排除文章:AWS Lambda - 运行时退出信号:已终止。
出版
要在 Visual Studio 中发布,只需右键单击项目并选择 "发布到 AWS Lambda...然后配置所需的设置。 有关更多信息,请访问AWS 网站。
试用!
您可以通过Lambda 控制台或通过 Visual Studio 激活 Lambda 函数。