如何在 AWS Lambda 上讀取和寫入條碼
本文提供了使用 IronBarcode 設置 AWS Lambda 函數的全面指南。 在本指南中,您將學習如何配置IronBarcode從S3存儲桶中讀取和寫入條碼。
How to Read & Write Barcode on AWS Lambda
安裝
本文將使用 S3 存儲桶,因此需要 AWSSDK.S3 套件。
使用 IronBarcode Zip
如果您使用 IronBarcode ZIP,必須設置臨時文件夾。
var awsTmpPath = @"/tmp/";
IronBarCode.Installation.DeploymentPath = awsTmpPath;
var awsTmpPath = @"/tmp/";
IronBarCode.Installation.DeploymentPath = awsTmpPath;
Dim awsTmpPath = "/tmp/"
IronBarCode.Installation.DeploymentPath = awsTmpPath
需要 Microsoft.ML.OnnxRuntime 套件來讀取條碼。 儘管在沒有它的情況下生成條碼運作良好,但讀取的預設模式依賴於機器學習 (ML)。 如果您切換到不使用 ML 的閱讀模式,則不需要該軟體包。
立即在您的專案中使用IronBarcode,並享受免費試用。
建立 AWS Lambda 專案
使用 Visual Studio,建立容器化的 AWS Lambda 是一個簡單的過程:
- 安裝 AWS Toolkit for Visual Studio
- 選擇「AWS Lambda 專案 (.NET Core - C#)」
選擇“.NET 8(容器映像)”藍圖,然後選擇“完成”。
新增套件依賴項
IronBarcode 庫在 .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 程式碼
此範例生成一個 EAN8 條碼,將其上傳到 S3 存儲桶,並讀取新創建的條碼。 使用 IronBarcode ZIP 時,配置臨時資料夾至關重要,因為該庫需要寫入許可權才能從 DLL 中複製運行時資料夾。
using Amazon.Lambda.Core;
using Amazon.S3;
using Amazon.S3.Model;
using IronBarCode;
// 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 IronBarcodeZipAwsLambda;
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)
{
var awsTmpPath = @"/tmp/";
IronBarCode.Installation.DeploymentPath = awsTmpPath;
IronBarCode.License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01";
string filename = Guid.NewGuid().ToString();
string bucketName = "deploymenttestbucket";
string objectKey = $"IronBarcodeZip/{filename}.png";
try
{
// Creating a barcode is as simple as:
var myBarcode = BarcodeWriter.CreateBarcode("1212345", BarcodeWriterEncoding.EAN8);
// Use pdfData (byte array) as needed
context.Logger.LogLine($"Barocde created.");
// Upload the PDF to S3
await UploadPngToS3Async(bucketName, objectKey, myBarcode.ToPngBinaryData());
context.Logger.LogLine($"Barocde uploaded successfully to {bucketName}/{objectKey}");
var resultFromByte = BarcodeReader.Read(myBarcode.ToPngBinaryData());
foreach (var item in resultFromByte)
{
// Log the read value out
context.Logger.LogLine($"Barcode value is = {item.Value}");
}
}
catch (Exception e)
{
context.Logger.LogLine($"[ERROR] FunctionHandler: {e.Message}");
}
}
// Function to upload the PNG file to S3
private async Task UploadPngToS3Async(string bucketName, string objectKey, byte[] pdfBytes)
{
using (var memoryStream = new MemoryStream(pdfBytes))
{
var request = new PutObjectRequest
{
BucketName = bucketName,
Key = objectKey,
InputStream = memoryStream,
ContentType = "image/png",
};
await _s3Client.PutObjectAsync(request);
}
}
}
using Amazon.Lambda.Core;
using Amazon.S3;
using Amazon.S3.Model;
using IronBarCode;
// 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 IronBarcodeZipAwsLambda;
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)
{
var awsTmpPath = @"/tmp/";
IronBarCode.Installation.DeploymentPath = awsTmpPath;
IronBarCode.License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01";
string filename = Guid.NewGuid().ToString();
string bucketName = "deploymenttestbucket";
string objectKey = $"IronBarcodeZip/{filename}.png";
try
{
// Creating a barcode is as simple as:
var myBarcode = BarcodeWriter.CreateBarcode("1212345", BarcodeWriterEncoding.EAN8);
// Use pdfData (byte array) as needed
context.Logger.LogLine($"Barocde created.");
// Upload the PDF to S3
await UploadPngToS3Async(bucketName, objectKey, myBarcode.ToPngBinaryData());
context.Logger.LogLine($"Barocde uploaded successfully to {bucketName}/{objectKey}");
var resultFromByte = BarcodeReader.Read(myBarcode.ToPngBinaryData());
foreach (var item in resultFromByte)
{
// Log the read value out
context.Logger.LogLine($"Barcode value is = {item.Value}");
}
}
catch (Exception e)
{
context.Logger.LogLine($"[ERROR] FunctionHandler: {e.Message}");
}
}
// Function to upload the PNG file to S3
private async Task UploadPngToS3Async(string bucketName, string objectKey, byte[] pdfBytes)
{
using (var memoryStream = new MemoryStream(pdfBytes))
{
var request = new PutObjectRequest
{
BucketName = bucketName,
Key = objectKey,
InputStream = memoryStream,
ContentType = "image/png",
};
await _s3Client.PutObjectAsync(request);
}
}
}
Imports Amazon.Lambda.Core
Imports Amazon.S3
Imports Amazon.S3.Model
Imports IronBarCode
' 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 IronBarcodeZipAwsLambda
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
Dim awsTmpPath = "/tmp/"
IronBarCode.Installation.DeploymentPath = awsTmpPath
IronBarCode.License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01"
Dim filename As String = Guid.NewGuid().ToString()
Dim bucketName As String = "deploymenttestbucket"
Dim objectKey As String = $"IronBarcodeZip/{filename}.png"
Try
' Creating a barcode is as simple as:
Dim myBarcode = BarcodeWriter.CreateBarcode("1212345", BarcodeWriterEncoding.EAN8)
' Use pdfData (byte array) as needed
context.Logger.LogLine($"Barocde created.")
' Upload the PDF to S3
Await UploadPngToS3Async(bucketName, objectKey, myBarcode.ToPngBinaryData())
context.Logger.LogLine($"Barocde uploaded successfully to {bucketName}/{objectKey}")
Dim resultFromByte = BarcodeReader.Read(myBarcode.ToPngBinaryData())
For Each item In resultFromByte
' Log the read value out
context.Logger.LogLine($"Barcode 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 PNG file to S3
Private Async Function UploadPngToS3Async(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/png"
}
Await _s3Client.PutObjectAsync(request)
End Using
End Function
End Class
End Namespace
在嘗試區塊之前,文件目的地被設置為 IronBarcodeZip 目錄,名稱生成為全球唯一標識符 (GUID)。 CreateBarcode
方法用於生成條碼。 之後,PNG 位元組陣列會傳遞至 Read
方法來讀取條碼。 這表明 AWS Lambda 函數能夠讀取條碼。
Read
方法也接受一個 BarcodeReaderOptions 對象,您可以自訂該對象以啟用各種功能,如讀取多個條碼、定位特定區域、使用異步和多執行緒處理、應用圖像校正濾鏡等等。
增加記憶體和超時時間
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 啟動 Lambda 函數。