如何在 AWS Lambda 上讀取和寫入 QR Code
這篇操作指南文章提供了使用IronQR設定AWS Lambda函數的詳細指引。 在本教程中,您將學習如何配置IronQR來直接讀寫QR碼至S3存儲桶。
如何在 AWS Lambda 上讀取和寫入 QR Code
安裝
這篇文章將使用 S3 存儲桶,所以AWSSDK.S3 套件是必需的。
立即在您的專案中使用IronQR,並享受免費試用。
建立 AWS Lambda 專案
使用 Visual Studio,建立容器化的 AWS Lambda 是一個簡單的過程:
- 安裝這個AWS 工具包 for Visual Studio
- 選擇「AWS Lambda 專案」(.NET Core - C#)请输入内容以便翻译。
選擇 “.NET 8”(容器映像)「藍圖」,然後選擇「完成」。
新增套件依賴項
IronQR 庫在 .NET 8 中運行於 AWS Lambda,不需要額外的依賴項。 要進行配置,請按以下顯示修改專案的Dockerfile: 請提供內容以進行翻譯。
FROM public.ecr.aws/lambda/dotnet:8
安裝必要的套件
執行 dnf 更新 -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);
}
}
}
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
增加記憶體和超時時間
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。