如何在 AWS Lambda 上讀取與寫入 QR 碼
這篇操作指南提供了使用 IronQR 設定 AWS Lambda 函式的詳細指引。 在本教學中,您將了解如何設定 IronQR,以便直接讀取和寫入 QR 碼至 S3 儲存桶。
如何在 AWS Lambda 上讀取與寫入 QR 碼
- 下載 C# 函式庫以讀取和寫入 QR 碼
- 建立 AWS Lambda 容器化專案範本
- 修改 Dockerfile 和 FunctionHandler 程式碼
- 增加記憶體與超時設定
- 部署並呼叫該函式,即可在 S3 中查看結果
安裝
本文將使用 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
# 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 程式碼
此範例將建立一個 QR 碼,將其上傳至 S3 儲存桶,並讀取新產生的 QR 碼。
檔案路徑位於 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);
/// <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);
}
}
}
}
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(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
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(bucketName As String, objectKey As String, jpgBytes As Byte()) As Task
Using memoryStream As New MemoryStream(jpgBytes)
Dim request As 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 函式的記憶體分配取決於文件的大小以及同時處理的數量。 作為起點,請在 aws-lambda-tools-defaults.json 中將記憶體設定為 512 MB,並將超時設定為 300 秒。
"function-memory-size" : 512,
"function-timeout" : 300
若記憶體不足,程式將拋出錯誤訊息:"執行時因錯誤而終止:訊號:被終止。"增加記憶體大小有助於解決此問題。 如需進一步指引,請參閱疑難排解文章:AWS Lambda - 執行時退出訊號:Killed。
發佈
要在 Visual Studio 中發佈,只需右鍵點擊專案並選擇"發佈至 AWS Lambda...",接著配置所需設定。 如需更多資訊,請造訪 AWS 網站。
立即試用!
您可以透過 Lambda 控制台或 Visual Studio 來啟動 Lambda 函式。
常見問題
如何將QR碼程式庫整合到我的C#專案中在AWS Lambda上?
您可以通過下載IronQR程式庫、使用Visual Studio建立容器化的AWS Lambda專案,並配置環境以支持QR碼操作,將像IronQR這樣的QR碼程式庫整合到您的C#專案中在AWS Lambda上。
配置IronQR用於AWS Lambda的步驟是什麼?
通過在Visual Studio中設置容器化專案模板,修改Dockerfile,更新FunctionHandler,並調整記憶體和超時設置,以確保順暢運行,配置IronQR用於AWS Lambda。
如何使用C#程式庫管理AWS S3的QR碼?
使用IronQR,您可以通過建立、上傳至AWS S3儲存桶及從中讀取來管理QR碼。這需結合使用IronQR程式庫和AWSSDK.S3包來處理與S3儲存桶的操作。
如果我用IronQR的AWS Lambda函式表現不佳,我該怎麼辦?
如果您的AWS Lambda函式表現不佳,請考慮在您的aws-lambda-tools-defaults.json檔案中增加記憶體和超時設置,以為該函式分配更多資源。
如何將C# Lambda函式部署到AWS?
通過使用Visual Studio的“發佈到AWS Lambda...”選項,配置必要的設置並利用AWS Toolkit進行部署,將C# Lambda函式部署到AWS。
是否可以在Visual Studio中測試我的AWS Lambda函式?
是的,您可以通過使用AWS Toolkit在Visual Studio中調用函式,並直接在開發環境中驗證其輸出,來測試您的AWS Lambda函式。
如何解決我的AWS Lambda函式的記憶體問題?
要排除記憶體問題,請在aws-lambda-tools-defaults.json檔案中增加函式的記憶體分配,並在重新部署後監控函式的性能。
在AWS Lambda專案中修改Dockerfile的重要性是什麼?
在AWS Lambda專案中修改Dockerfile對於正確設置環境非常重要,包括更新倉庫和複製執行函式所需的構建工件。
如何確保我的AWS Lambda函式能有效處理QR碼操作?
通過優化記憶體和超時設置、使用像IronQR這樣合適的程式庫,以及正確配置Dockerfile和專案設置,確保您的AWS Lambda函式能有效處理QR碼操作。
我可以在AWS Lambda中自動化QR碼生成和檢索嗎?
是的,您可以使用IronQR在AWS Lambda中自動化QR碼的生成和檢索。這個程式庫允許您以程式方式建立QR碼、將其上傳到S3,並根據需要讀取回來。

