如何在 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.Co/re;
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.Co/re;
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
Imports System.IO
Imports System.Threading.Tasks
' 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 碼函式庫整合到我的 AWS Lambda C# 專案中?
您可透過下載 IronQR程式庫、使用 Visual Studio 建立容器化的 AWS Lambda 專案,並配置環境以支援 QR 碼操作,將 IronQR 等 QR 碼函式庫整合至您的 AWS Lambda C# 專案中。
配置 IronQR 用於 AWS Lambda 的步驟為何?
透過在 Visual Studio 中建立容器化專案範本、修改 Dockerfile、更新 FunctionHandler,以及調整記憶體和超時設定,來為 AWS Lambda 配置 IronQR,以確保運作順暢。
如何使用 C# 函式庫透過 AWS S3 管理 QR 碼?
透過 IronQR,您可以透過建立、上傳至以及從 AWS S3 儲存桶讀取資料來管理 QR 碼。這涉及結合使用 IronQR程式庫與 AWSSDK.S3 套件,以處理 S3 儲存桶的相關操作。
如果我的 AWS Lambda 函式在使用 IronQR 時表現不佳,該怎麼辦?
若您的 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,並在需要時讀取回來。

