AWS Lambda'da Barkod Okuma ve Yazma
Bu nasıl yapılır makalesi, IronBarcode kullanarak bir AWS Lambda işlevinin nasıl kurulacağına dair kapsamlı bir kılavuz sağlar. Bu kılavuzda, IronBarcode'un bir S3 kovasından nasıl okuyup nasıl yazacak şekilde yapılandırılacağını öğreneceksiniz.
AWS Lambda'da Barkod Okuma ve Yazma
- Barkod okuyup yazmak için bir C# kütüphanesi indirin
- Proje şablonunu oluşturun ve seçin
- FunctionHandler kodunu düzenleyin
- Projeyi yapılandırın ve dağıtın
- İşlevi çalıştırın ve sonuçları S3'te kontrol edin
Kurulum
Bu makalede bir S3 bucket kullanılacak, bu yüzden AWSSDK.S3 paketi gereklidir.
IronBarcode Zip Kullanımı
IronBarcode ZIP kullanıyorsanız, geçici klasörü ayarlamak önemlidir.
var awsTmpPath = @"/tmp/";
IronBarCode.Installation.DeploymentPath = awsTmpPath;Dim awsTmpPath = "/tmp/"
IronBarCode.Installation.DeploymentPath = awsTmpPathDim awsTmpPath = "/tmp/"
IronBarCode.Installation.DeploymentPath = awsTmpPathMicrosoft.ML.OnnxRuntime paketi, barkodları okumak için gereklidir. Barkod yazma, doğru çalışmakla birlikte, okuma için varsayılan mod makine öğrenmesine (ML) dayanır. ML kullanmayan bir okuma moduna geçerseniz, paket gerekli değildir.
Bir AWS Lambda Projesi Oluşturun
Visual Studio ile, kapsayıcılaştırılmış bir AWS Lambda oluşturmak kolay bir işlemdir:
- Visual Studio için AWS Toolkit'i yükleyin
- 'AWS Lambda Projesi (.NET Core - C#)' seçin
- '.NET 8 (Kapsayıcı Görüntü)' şablonunu seçin, ardından 'Bitir' seçin.

Paket Bağımlılıklarını Ekleyin
.NET 8'deki IronBarcode kütüphanesi, ek bağımlılıklara ihtiyaç duymadan AWS Lambda üzerinde çalışır. Kurulumunu yapmak için, projenizin Dockerfile'ını aşağıdaki şekilde güncelleyin:
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 Kodunu Düzenleyin
Bu örnek, bir EAN8 barkodu oluşturur, S3 kovasına yükler ve yeni oluşturulan barkodu okur. IronBarcode ZIP kullanırken, kütüphanenin DLL'lerden çalışma zamanı klasörünü kopyalamak için yazma izinlerine ihtiyaç duyması nedeniyle geçici klasörün yapılandırılması çok önemlidir.
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 NamespaceImports 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 NamespaceTry bloğundan önce, dosya hedefi IronBarcodeZip dizinine ayarlanır ve adı evrensel olarak benzersiz bir tanımlayıcı (GUID) olarak üretilir. CreateBarcode yöntemi barkod oluşturmak için kullanılır. Sonrasında, PNG byte dizisi barkodu okumak için Read yöntemine aktarılır. Bu, AWS Lambda işlevinin barkodları okuyabileceğini gösterir.
Read yöntemi ayrıca, BarcodeReaderOptions nesnesini kabul eder. Bu nesneyi birden fazla barkod okuma, belirli alanları hedefleme, asenkron ve çok iş parçacıklı işlem kullanma, görüntü düzeltme filtreleri uygulama gibi özellikleri etkinleştirmek üzere özelleştirebilirsiniz.
Bellek ve Zaman Aşımını Artırın
Lambda fonksiyonunda tahsis edilen bellek miktarı, işlenen belgelerin boyutuna ve aynı anda işlenen belge sayısına bağlı olarak değişecektir. Temel olarak, belleği 512 MB ve süre aşımını 300 saniye olarak aws-lambda-tools-defaults.json ile ayarlayın.
{
"function-memory-size": 512,
"function-timeout": 300
}
Bellek yetersiz olduğunda, program 'Çalışma zamanı hatayla çıktı: sinyal: öldürüldü.' hatasını verecektir. Bellek boyutunu artırmak bu sorunu çözebilir. Daha fazla detay için sorun giderme makalesine bakın: AWS Lambda - Çalışma İstem Çıkışı: Öldürüldü.
Yayınla
Visual Studio'da yayınlamak için, proje üzerine sağ tıklayın ve 'AWS Lambda'ya Yayınla...' seçin, ardından gerekli ayarları yapılandırın. Bir Lambda'yı yayınlama hakkında daha fazla bilgi için AWS web sitesini okuyabilirsiniz.
Deneyin!
Lambda işlevini ya Lambda konsolu ya da Visual Studio üzerinden etkinleştirebilirsiniz.
Sıkça Sorulan Sorular
AWS Lambda'da IronBarcode'u nasıl kurarım?
AWS Lambda'da IronBarcode'u kurmak için, Visual Studio kullanarak bir AWS Lambda projesi oluşturmanız, AWSSDK.S3 gibi gerekli paketleri kurmanız, IronBarcode dağıtım yolunu yapılandırmanız ve bir S3 kovasına barkod okumak ve yazmak için FunctionHandler kodunu yazmanız gerekir.
AWS Lambda'da IronBarcode kullanmak için hangi paketlere ihtiyaç var?
Varsayılan makine öğrenimi okuma modunu kullandığınızı varsayarak, S3 kovalarını yönetmek için AWSSDK.S3 ve barkod okumak için Microsoft.ML.OnnxRuntime paketine ihtiyacınız var.
AWS Lambda için Dockerfile içine nasıl IronBarcode yükleyebilirim?
Dockerfile'ınızda, .NET Lambda projesinin derleme çıktısını içeri kopyalayın ve AWS Lambda ortamı için IronBarcode dağıtım yolunu yapılandırın.
AWS Lambda'da IronBarcode için bir lisans anahtarı gerekiyor mu?
Evet, AWS Lambda fonksiyonu içinde IronBarcode kullanmak için lisans anahtarınızı FunctionHandler kodunda ayarlamanız gerekmektedir.
AWS Lambda'da IronBarcode ile barkod okurken hangi seçenekleri özelleştirebilirim?
AWS Lambda'da IronBarcode kullanırken, birden fazla barkod okuma, belirli görüntü alanlarını hedefleme ve BarcodeReaderOptions nesnesi aracılığıyla asenkron işlem gibi seçenekleri özelleştirebilirsiniz.
AWS Lambda'da IronBarcode kullanarak geçici klasör yapılandırmasını nasıl yönetebilirim?
AWS Lambda FunctionHandler'ınızda IronBarcode için DeploymentPath'ı '/tmp/' olarak atayarak geçici klasör yapılandırmanızı ayarlayın.
IronBarcode kullanan AWS Lambda fonksiyonum bellekten tükenirse ne yapmalıyım?
aws-lambda-tools-defaults.json dosyasındaki 'function-memory-size' ayarını kullanarak Lambda fonksiyonunuza ayrılan belleği artırın ve iş yükünüz için uygun şekilde ayarlandığından emin olun.
AWS Lambda'da IronBarcode kullanarak bir barkod görüntüsünü S3 kovasına nasıl yüklerim?
IronBarcode kullanarak bir barkod oluşturun, bunu PNG ikili verisine dönüştürün ve belirtilen S3 kovasına bu veriyi yüklemek için Amazon S3 istemcisini kullanın.
AWS Lambda'da OnnxRuntime kullanmadan barkod oluşturabilir ve okuyabilir miyim?
Evet, OnnxRuntime kullanmadan barkod oluşturabilir ve yazabilirsiniz, ancak varsayılan makine öğrenimi modunu kullanıyorsanız okumak için OnnxRuntime'a ihtiyaç vardır. Kullanmak istemiyorsanız bir ML olmayan okuma moduna geçiş yapın.
IronBarcode kullanan bir AWS Lambda fonksiyonu nasıl yayımlanır?
Visual Studio'da projenize sağ tıklayın ve 'Publish to AWS Lambda' seçeneğini belirleyin. Dağıtım için gerekli ayarları yapın ve işlemi tamamlamak için AWS yönergelerini izleyin.
Curtis Chau, Bilgisayar Bilimleri alanında Lisans Derecesine (Carleton Üniversitesi) sahip ve Node.js, TypeScript, JavaScript ve React konularında uzmanlaşmış ön uç geliştirmeyle ilgileniyor. Sezgisel ve estetik açıdan hoş kullanıcı arayüzleri oluşturma tutkunu, Curtis modern çerçevelerle çalışmayı ve iyi yapılandırılmış, görsel olarak çekici kılavuzlar oluşturmayı seviyor.