如何在AWS Lambda上讀取與寫入條碼
此操作文章提供了一個綜合指南,教您如何使用IronBarcode設置AWS Lambda函式。 在本指南中,您將學習如何配置IronBarcode從S3桶中讀取和寫入條碼。
如何在AWS Lambda上讀取與寫入條碼
- 下載C#庫以讀取和寫入條碼
- 建立並選擇專案範本
- 修改FunctionHandler程式碼
- 配置並部署專案
- 調用函式並檢查S3中的結果
安裝
本文將使用S3桶,因此需要AWSSDK.S3包。
使用IronBarcode Zip
如果您使用IronBarcode ZIP,則需要設置臨時文件夾。
:path=/static-assets/barcode/content-code-examples/get-started/aws-1.cs
var awsTmpPath = @"/tmp/";
IronBarCode.Installation.DeploymentPath = awsTmpPath;
Dim awsTmpPath As String = "/tmp/"
IronBarCode.Installation.DeploymentPath = awsTmpPath
讀取條碼需要Microsoft.ML.OnnxRuntime包。 雖然寫入條碼不需要它,但預設的讀取模式依賴於機器學習(ML)。 如果您切換到不使用ML的讀取模式,則不需要該包。
建立AWS Lambda專案
使用Visual Studio,建立容器化的AWS Lambda是一個簡單的過程:
- 安裝Visual Studio的AWS Toolkit
- 選擇"AWS Lambda Project (.NET Core - C#)"
- 選擇".NET 8 (Container Image)"藍圖,然後選擇"完成"。
選擇容器映像
新增包依賴性
.NET 8中的IronBarcode程式庫在AWS Lambda上工作而不需要額外的依賴性。 要設置它,請按以下方式更新專案的Dockerfile:
FROM public.ecr.aws/lambda/dotnet:8
# Install necessary packages
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程式碼
此範例生成EAN8條碼,將其上傳到S3桶中,並讀取新建立的條碼。 使用IronBarcode ZIP時,配置臨時文件夾至關重要,因為該程式庫需要寫入權限以從DLLs中拷貝運行時文件夾。
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);
/// <summary>
/// AWS Lambda Function Handler. It generates a barcode, uploads it to S3, and then reads it.
/// </summary>
/// <param name="context">The ILambdaContext that provides methods for logging and describing the Lambda environment.</param>
public async Task FunctionHandler(ILambdaContext context)
{
var awsTmpPath = @"/tmp/";
IronBarCode.Installation.DeploymentPath = awsTmpPath;
// Set your IronBarcode license key here
IronBarCode.License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01";
string filename = Guid.NewGuid().ToString();
string bucketName = "deploymenttestbucket";
string objectKey = $"IronBarcodeZip/{filename}.png";
try
{
// Creating a barcode with EAN8 encoding
var myBarcode = BarcodeWriter.CreateBarcode("1212345", BarcodeWriterEncoding.EAN8);
context.Logger.LogLine($"Barcode created.");
// Upload the PNG image of the barcode to the specified S3 bucket
await UploadPngToS3Async(bucketName, objectKey, myBarcode.ToPngBinaryData());
context.Logger.LogLine($"Barcode uploaded successfully to {bucketName}/{objectKey}");
// Read and log the barcode value from the PNG binary data
var resultFromByte = BarcodeReader.Read(myBarcode.ToPngBinaryData());
foreach (var item in resultFromByte)
{
context.Logger.LogLine($"Barcode value is = {item.Value}");
}
}
catch (Exception e)
{
context.Logger.LogLine($"[ERROR] FunctionHandler: {e.Message}");
}
}
/// <summary>
/// Uploads a PNG byte array to the specified S3 bucket.
/// </summary>
/// <param name="bucketName">The name of the S3 bucket.</param>
/// <param name="objectKey">The object key for the uploaded file in the bucket.</param>
/// <param name="pdfBytes">Byte array of the PNG to be uploaded.</param>
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);
/// <summary>
/// AWS Lambda Function Handler. It generates a barcode, uploads it to S3, and then reads it.
/// </summary>
/// <param name="context">The ILambdaContext that provides methods for logging and describing the Lambda environment.</param>
public async Task FunctionHandler(ILambdaContext context)
{
var awsTmpPath = @"/tmp/";
IronBarCode.Installation.DeploymentPath = awsTmpPath;
// Set your IronBarcode license key here
IronBarCode.License.LicenseKey = "IRONBARCODE-MYLICENSE-KEY-1EF01";
string filename = Guid.NewGuid().ToString();
string bucketName = "deploymenttestbucket";
string objectKey = $"IronBarcodeZip/{filename}.png";
try
{
// Creating a barcode with EAN8 encoding
var myBarcode = BarcodeWriter.CreateBarcode("1212345", BarcodeWriterEncoding.EAN8);
context.Logger.LogLine($"Barcode created.");
// Upload the PNG image of the barcode to the specified S3 bucket
await UploadPngToS3Async(bucketName, objectKey, myBarcode.ToPngBinaryData());
context.Logger.LogLine($"Barcode uploaded successfully to {bucketName}/{objectKey}");
// Read and log the barcode value from the PNG binary data
var resultFromByte = BarcodeReader.Read(myBarcode.ToPngBinaryData());
foreach (var item in resultFromByte)
{
context.Logger.LogLine($"Barcode value is = {item.Value}");
}
}
catch (Exception e)
{
context.Logger.LogLine($"[ERROR] FunctionHandler: {e.Message}");
}
}
/// <summary>
/// Uploads a PNG byte array to the specified S3 bucket.
/// </summary>
/// <param name="bucketName">The name of the S3 bucket.</param>
/// <param name="objectKey">The object key for the uploaded file in the bucket.</param>
/// <param name="pdfBytes">Byte array of the PNG to be uploaded.</param>
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)
''' <summary>
''' AWS Lambda Function Handler. It generates a barcode, uploads it to S3, and then reads it.
''' </summary>
''' <param name="context">The ILambdaContext that provides methods for logging and describing the Lambda environment.</param>
Public Async Function FunctionHandler(ByVal context As ILambdaContext) As Task
Dim awsTmpPath = "/tmp/"
IronBarCode.Installation.DeploymentPath = awsTmpPath
' Set your IronBarcode license key here
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 with EAN8 encoding
Dim myBarcode = BarcodeWriter.CreateBarcode("1212345", BarcodeWriterEncoding.EAN8)
context.Logger.LogLine($"Barcode created.")
' Upload the PNG image of the barcode to the specified S3 bucket
Await UploadPngToS3Async(bucketName, objectKey, myBarcode.ToPngBinaryData())
context.Logger.LogLine($"Barcode uploaded successfully to {bucketName}/{objectKey}")
' Read and log the barcode value from the PNG binary data
Dim resultFromByte = BarcodeReader.Read(myBarcode.ToPngBinaryData())
For Each item In resultFromByte
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
''' <summary>
''' Uploads a PNG byte array to the specified S3 bucket.
''' </summary>
''' <param name="bucketName">The name of the S3 bucket.</param>
''' <param name="objectKey">The object key for the uploaded file in the bucket.</param>
''' <param name="pdfBytes">Byte array of the PNG to be uploaded.</param>
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
在try塊之前,文件目的地設置為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 - Runtime Exited Signal: Killed。
發佈
要在Visual Studio中發佈,右鍵單擊專案並選擇"Publish to AWS Lambda...",然後配置所需的設置。 您可以在AWS網站上了解更多有關發佈Lambda的資訊。
試試看!
您可以通過Lambda控制台或Visual Studio激活Lambda函式。
常見問題
如何在AWS Lambda上設置條形碼的讀取和寫入?
要在AWS Lambda上設置條形碼的讀取和寫入,請使用IronBarcode程式庫,下載它並使用Visual Studio建立一個AWS Lambda項目。修改FunctionHandler的程式碼以處理條形碼操作,配置專案設定並部署。確保包括如AWSSDK.S3的必要套件依賴。
在AWS Lambda上條形碼處理需要什麼套件?
對於在AWS Lambda上的條形碼處理,請包括用於S3交互的AWSSDK.S3套件,以及可選的Microsoft.ML.OnnxRuntime套件進行高級機器學習條形碼讀取,若使用標準條形碼讀取方法則可能並不需要。
如何在AWS Lambda中修改FunctionHandler程式碼以進行條形碼任務?
修改FunctionHandler程式碼來生成和讀取條形碼,使用IronBarcode。請確保設置IronBarcode許可金鑰並配置臨時文件夾以便順利運行IronBarcode ZIP文件。
如何增加AWS Lambda功能的記憶體和超時以處理條形碼?
在aws-lambda-tools-defaults.json文件中調整記憶體和超時設置,將function-memory-size設置為512 MB,將function-timeout設置為300秒,以滿足IronBarcode的條形碼處理需求。
如何使用Visual Studio發布用於條形碼處理的Lambda功能?
右鍵單擊Visual Studio中的專案,選擇“發佈到AWS Lambda...”,並配置設置以發布Lambda功能。按照AWS文件獲取詳細步驟,確保IronBarcode正確設置。
如何測試已部署的AWS Lambda功能的條形碼操作?
通過AWS Lambda控制台或直接從Visual Studio激活來測試Lambda功能,確保IronBarcode正常運作和條形碼處理任務按預期完成。
Dockerfile在設置AWS Lambda上的條形碼處理中起什麼作用?
Dockerfile可以更新必要的程式包並將.NET Lambda專案的構建工件複製到圖像中,從而使IronBarcode在AWS Lambda上的條形碼處理更加順暢。
在AWS Lambda上使用條形碼庫時為何設置臨時文件夾很重要?
設置臨時文件夾是必要的,因為IronBarcode需要寫入權限來進行ZIP操作,確保從DLLs正確複製運行時間文件夾,以便在AWS Lambda上順利運行。
我可以在AWS Lambda上自定義條形碼讀取嗎?
可以,IronBarcode允許使用BarcodeReaderOptions自定義條形碼讀取,這包括讀取多個條形碼、定位特定區域、啟用異步處理和應用圖像校正過濾器。
在條形碼處理期間遇到“Runtime exited with error: signal: killed”錯誤時該怎麼辦?
此錯誤表明記憶體分配不足。在aws-lambda-tools-defaults.json文件中增加Lambda功能的記憶體以解決此問題,當使用IronBarcode時。

