QR Kodları AWS Lambda'da Okuma ve Yazma

This article was translated from English: Does it need improvement?
Translated
View the article in English
Amazon Lambda Architecture Logo related to QR Kodları AWS Lambda'da Okuma ve Yazma

Bu nasıl yapılır makalesi, IronQR ile bir AWS Lambda işlevi ayarlamak için ayrıntılı bir kılavuz sunar. Bu öğreticide, IronQR'yi bir S3 kovasına doğrudan QR kodlarını okumak ve yazmak için nasıl yapılandıracağını keşfedeceksiniz.

Kurulum

Bu makale bir S3 kovası kullanacak, bu nedenle AWSSDK.S3 paketi gereklidir.

!{--0100110001001001010000100101001001000001010100100101100101011111--}

Bir AWS Lambda Projesi Oluşturun

Visual Studio ile bir kaplamalı AWS Lambda oluşturmak kolay bir süreçtir:

Kapsayıcı resmi seç

Paket Bağımlılıklarını Ekleyin

.NET 8'deki IronQR kütüphanesi, ek ek bağımlılıklar gerektirmeden AWS Lambda üzerinde çalışır. Onu yapılandırmak için, projenin Dockerfile dosyasını aşağıda gösterildiği gibi değiştirin:

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 Kodunu Değiştirin

Bu örnek bir QR kodu oluşturur, S3 kovasına yükler ve yeni oluşturulan QR kodunu okur.

Dosya yolu, IronQrNuGet dizininde belirtilmiştir ve dosya adı olarak küresel olarak benzersiz bir tanımlayıcı (GUID) kullanılır. Write yöntemi, sağlanan değere göre QR kodunu oluşturur ve ortaya çıkan JPG bayt dizisi, QR kodunu okumak için Read yöntemine iletilir. Bu, bu AWS Lambda işlevinin QR kodlarını okuyabilme yeteneğini gösterir.

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);

        /// <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.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);

        /// <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

' 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
$vbLabelText   $csharpLabel

Bellek ve Zaman Aşımı Artırın

Lambda işlevi için bellek tahsisi, belgelerin boyutuna ve eşzamanlı işlenen sayılarına bağlıdır. Başlangıç ​​noktasında, aws-lambda-tools-defaults.json içinde belleği 512 MB ve zaman aşımını 300 saniye olarak ayarlayın.

"function-memory-size" : 512,
"function-timeout" : 300

Bellek yetersizse, program şu hatayı verecektir: 'Çalışma zamanı hatasıyla durdu: sinyal: öldürüldü.' Bellek boyutunu artırmak bu sorunu çözebilir. Daha fazla rehberlik için, sorun giderme makalesine bakın: AWS Lambda - Çalışma Süresi Sinyal: Öldürüldü.

Yayınla

Visual Studio'da yayınlamak için, projeye sağ tıklayın ve 'AWS Lambda'ya Yayınla...' seçeneğini tercih edin. Ardından gerekli ayarları yapılandırın. Daha fazla bilgi için AWS web sitesini ziyaret edin.

Dene!

Lambda işlevini ya Lambda konsolu ya da Visual Studio aracılığıyla etkinleştirebilirsiniz.

Sıkça Sorulan Sorular

QR kod kütüphanesini AWS Lambda'de C# projemde nasil entegre edebilirim?

IronQR gibi bir QR kod kütüphanesini AWS Lambda uzerinde C# projenize entegre etmek için, IronQR kütüphanesini indirerek, Visual Studio kullanarak bir konteynerize AWS Lambda projesi oluşturarak ve ortamınızı QR kodu işlemleri için destekleyecek şekilde konfigure ederek bunu gerceklestirebilirsiniz.

AWS Lambda için IronQR nasil konfigure edilir?

IronQR'yi AWS Lambda için konfigure edin: Visual Studio'da bir konteynerize proje şablonu ayarlayin, Dockerfile'i değiştirin, FunctionHandler'i yukleyin ve duzgun calisma için bellek ve zaman asimi ayarlarini ayarlayin.

C# kütüphanesi kullanarak AWS S3 ile QR kode nasil yönetirim?

IronQR kullanarak, QR kodlari oluşturarak, AWS S3 bucket'lara yukleyerek ve onlardan okuyarak yönetebilirsiniz. Bu, IronQR kütüphanesinin S3 bucket'lar ile işlem yaparken AWSSDK.S3 paketi ile birlikte kullanilmasini gerektirir.

IronQR kullanan AWS Lambda fonksiyonum iyi performans göstermiyorsa ne yapmaliyim?

AWS Lambda fonksiyonunuz iyi performans göstermiyorsa, aws-lambda-tools-defaults.json dosyanizda bellek ve zaman asimi ayarlarini artirmayi dusunun, bu işlev için daha fazla kaynak ayirir.

C# Lambda fonksiyonunu AWS'ye nasil deploy ederim?

C# Lambda fonksiyonunu AWS'ye deploy edin: Visual Studio'nun 'Publish to AWS Lambda...' seceniğini kullanarak gereklilikleri konfigure edin ve AWS Toolkit'i kullanarak deploy işlemini gerceklestirin.

AWS Lambda fonksiyonumu Visual Studio'da test etmek mumkun mu?

Evet, AWS Lambda fonksiyonunuzu Visual Studio'da AWS Toolkit'i kullanarak test edebilir ve çıktısını doğrudan geliştirme ortamında doğrulayabilirsiniz.

AWS Lambda fonksiyonumda bellek sorunlarini nasil cozerim?

Bellek sorunlarini çözümlemek için, aws-lambda-tools-defaults.json dosyasında fonksiyonun bellek ayırımını artırın ve yeniden dağıtımdan sonra fonksiyonun performansını izleyin.

AWS Lambda projesinde Dockerfile'i değiştirmenin önemi nedir?

AWS Lambda projesinde Dockerfile değiştirmek gereklidir, cunku ortamı doğru kurmak için gereklidir; repositorieleri guncelleyip, fonksiyonun doğru calismasını saglamak için gerekli oluşturma artefaktlarini kopyalamaniz gerekir.

AWS Lambda fonksiyonumun QR kodu işlemlerini verimli bir şekilde yönetmesini nasil saglarim?

AWS Lambda fonksiyonunuzun QR kodu işlemlerini verimli bir şekilde yönetmesini saglayin: bellek ve zaman asimi ayarlarını optimize edin, IronQR gibi doğru kütüphaneleri kullanin ve Dockerfile ve proje ayarlarini doğru yapi.

AWS Lambda'da QR kodu oluşturma ve alma işlemlerini otomatiklestirmek mumkun mu?

Evet, IronQR kullanarak AWS Lambda'da QR kodu oluşturma ve alma işlemlerini otomatiklestirebilirsiniz. Kütüphane, programlı olarak QR kodu oluşturmanıza, S3'e yuklemenize ve gerekirse onları geri okumanıza olanak tanir.

Curtis Chau
Teknik Yazar

Curtis Chau, Bilgisayar Bilimleri alanında lisans derecesine sahiptir (Carleton Üniversitesi) ve Node.js, TypeScript, JavaScript ve React konularında uzmanlaşmış ön uç geliştirme üzerine uzmanlaşmıştır. Kullanıcı dostu ve estetik açıdan hoş arayüzler tasarlamaya tutkuyla bağlı olan Curtis, modern çerç...

Daha Fazlasını Oku
Başlamaya Hazır mısınız?
Nuget İndirmeler 64,787 | Sürüm: 2026.4 just released
Still Scrolling Icon

Hala Kaydiriyor musunuz?

Hızlı bir kanit mi istiyorsunuz? PM > Install-Package IronQR
bir örneği çalıştır URL'inin bir QR koduna dönüşünü izle.