如何在 AWS Lambda 上读取和写入二维码
本文提供了使用 IronQR 设置 AWS Lambda 函数的详细指南。 在本教程中,您将学习如何配置 IronQR,以便直接向 S3 存储桶读取和写入二维码。
如何在 AWS Lambda 上读取和写入二维码
- 下载用于读取和写入QR码的C#库
- 创建 AWS Lambda 容器化项目模板
- 修改 Dockerfile 和 FunctionHandler 代码
- 增加内存和超时设置
- 部署并调用函数以在 S3 中查看结果
安装
本文将使用S3存储桶,因此需要AWSSDK.S3包。
从今天开始在您的项目中使用 IronQR 免费试用。
创建 AWS Lambda 项目
使用 Visual Studio 创建容器化的 AWS Lambda 是一个简单的过程:
- 安装AWS Toolkit for Visual Studio
- 选择 'AWS Lambda Project (.NET Core - C#)'
- 选择 '.NET 8 (Container Image)' 蓝图,然后选择 '完成'。

添加包依赖项
.NET 8 中的 IronQR 库可在 AWS Lambda 上运行,无需额外的依赖项。 要进行配置,请按如下所示修改项目的 Dockerfile:
FROM public.ecr.aws/lambda/dotnet:8
# Install necessary packages and update repositories
RUN dnf update -y
WORKDIR /var/task
# This COPY command copies the .NET Lambda project's build artifacts from the host machine into the image.
# The source of the COPY should match where the .NET Lambda project publishes its build artifacts. If the Lambda function is being built
# with the AWS .NET Lambda Tooling, the `--docker-host-build-output-dir` switch controls where the .NET Lambda project
# will be built. The .NET Lambda project templates default to having `--docker-host-build-output-dir`
# set in the aws-lambda-tools-defaults.json file to "bin/Release/lambda-publish".
#
# Alternatively, Docker multi-stage build could be used to build the .NET Lambda project inside the image.
# For more information on this approach, check out the project's README.md file.
COPY "bin/Release/lambda-publish" .
修改 FunctionHandler 代码
本示例生成一个二维码,将其上传到 S3 存储桶,并读取新生成的二维码。
文件路径在 IronQrNuget 目录中指定,文件名使用全局唯一标识符 (GUID)。 Write 方法根据提供的值生成QR码,生成的JPG字节数组随后传递给 Read 方法以读取QR码。 这证明该 AWS Lambda 函数能够读取二维码。
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);
/// <summary>
/// Main handler for AWS Lambda
/// </summary>
/// <param name="context">The ILambdaContext that provides methods for logging and describing the Lambda environment.</param>
/// <returns></returns>
public async Task FunctionHandler(ILambdaContext context)
{
// Set the license key for IronQR
IronQr.License.LicenseKey = "IronQR-MYLICENSE-KEY-1EF01";
string bucketName = "deploymenttestbucket";
string objectKey = $"IronQrNuget/{Guid.NewGuid()}.png";
try
{
// Create a QR code with the content "12345"
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}");
// Read the QR code
QrImageInput imageInput = new QrImageInput(myQr.Save());
QrReader reader = new QrReader();
var resultFromByte = reader.Read(imageInput);
foreach (var item in resultFromByte)
{
// Log the read value
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[] jpgBytes)
{
using (var memoryStream = new MemoryStream(jpgBytes))
{
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)
''' <summary>
''' Main handler for AWS Lambda
''' </summary>
''' <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
' Set the license key for IronQR
IronQr.License.LicenseKey = "IronQR-MYLICENSE-KEY-1EF01"
Dim bucketName As String = "deploymenttestbucket"
Dim objectKey As String = $"IronQrNuget/{Guid.NewGuid()}.png"
Try
' Create a QR code with the content "12345"
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}")
' Read the QR code
Dim imageInput As New QrImageInput(myQr.Save())
Dim reader As New QrReader()
Dim resultFromByte = reader.Read(imageInput)
For Each item In resultFromByte
' Log the read value
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 jpgBytes() As Byte) As Task
Using memoryStream As New MemoryStream(jpgBytes)
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 NamespaceImports 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)
''' <summary>
''' Main handler for AWS Lambda
''' </summary>
''' <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
' Set the license key for IronQR
IronQr.License.LicenseKey = "IronQR-MYLICENSE-KEY-1EF01"
Dim bucketName As String = "deploymenttestbucket"
Dim objectKey As String = $"IronQrNuget/{Guid.NewGuid()}.png"
Try
' Create a QR code with the content "12345"
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}")
' Read the QR code
Dim imageInput As New QrImageInput(myQr.Save())
Dim reader As New QrReader()
Dim resultFromByte = reader.Read(imageInput)
For Each item In resultFromByte
' Log the read value
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 jpgBytes() As Byte) As Task
Using memoryStream As New MemoryStream(jpgBytes)
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增加内存和超时
Lambda 函数的内存分配取决于文档的大小和同时处理的文档数量。 作为起点,将内存设置为512 MB,并在aws-lambda-tools-defaults.json中设置超时时间为300秒。
"function-memory-size" : 512,
"function-timeout" : 300
如果内存不足,程序将引发错误:“运行时错误退出:信号:终止”。增加内存大小可以帮助解决此问题。 欲获取进一步指导,请查看故障排除文章:AWS Lambda - 运行时退出信号:已终止。
发布
要在 Visual Studio 中发布,只需右键单击项目,然后选择“发布到 AWS Lambda...” 然后,配置所需的设置。 如需更多信息,请访问AWS网站。
试一试!
您可以通过Lambda控制台或通过Visual Studio激活Lambda函数。
常见问题
如何在AWS Lambda上设置IronQR?
要在AWS Lambda上设置IronQR,您需要在Visual Studio中创建一个容器化项目,添加IronQR库,配置依赖项,修改Dockerfile,并以适当的内存和超时设置部署功能。
在AWS Lambda上使用IronQR需要哪些先决条件?
您需要Visual Studio、Visual Studio的AWS Toolkit、用于S3 bucket交互的AWSSDK.S3包以及IronQR库。
IronQR可以直接读写S3 bucket上的QR码吗?
是的,IronQR可以配置为在AWS Lambda上直接读取和写入S3 bucket中的QR码。
如何增加IronQR在AWS Lambda上的内存和超时设置?
您可以通过调整aws-lambda-tools-defaults.json文件中的'function-memory-size'和'function-timeout'字段来增加内存和超时设置。
IronQR库如何集成到.NET 8的容器化项目中?
通过将库添加到项目中、修改Dockerfile并设置FunctionHandler以使用IronQR创建和读取QR码来进行集成。
如果Lambda功能内存不足,我该怎么办?
如果功能内存不足,请尝试增加aws-lambda-tools-defaults.json文件中的内存分配设置,并确保其有足够的资源高效运行。
如何使用IronQR部署AWS Lambda功能?
通过为AWS Lambda配置项目,如果需要,增加内存和超时设置,然后使用Visual Studio将项目发布到AWS Lambda来部署功能。
IronQR在AWS Lambda上工作需要额外的设置吗?
在使用.NET 8时,除了标准的AWS设置外,IronQR在AWS Lambda上工作不需要额外的依赖项。
在Visual Studio中将带有IronQR的项目发布到AWS Lambda需要什么?
要发布,请右键点击项目,选择'发布到AWS Lambda...',并在发布对话框中配置必要的设置。
如何使用IronQR测试已部署的Lambda功能?
您可以通过AWS Lambda控制台或在部署后直接从Visual Studio激活并测试Lambda功能。
Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。