Como ler e gravar códigos QR no AWS Lambda
Este artigo explicativo oferece um guia detalhado para configurar uma função AWS Lambda com o IronQR. Neste tutorial, você descobrirá como configurar o IronQR para ler e gravar códigos QR diretamente em um bucket do S3.
Como ler e gravar códigos QR no AWS Lambda
- Baixar uma biblioteca C# para ler e escrever códigos QR
- Crie o modelo de projeto conteinerizado do AWS Lambda
- Modifique o código do Dockerfile e do FunctionHandler.
- Aumente as configurações de memória e tempo limite.
- Implante e invoque a função para ver os resultados no S3.
Instalação
Este artigo usará um bucket S3, portanto, o pacote AWSSDK.S3 é necessário.
Comece a usar IronQR em seu projeto hoje com uma avaliação gratuita.
Criar um projeto AWS Lambda
Com o Visual Studio, criar uma instância AWS Lambda em contêiner é um processo fácil:
- Instale o AWS Toolkit for Visual Studio
- Selecione um 'Projeto AWS Lambda (.NET Core - C#)'
- Selecione um modelo ' .NET 8 (Imagem de Contêiner)' e, em seguida, selecione 'Concluir'.

Adicionar dependências de pacotes
A biblioteca IronQR no .NET 8 funciona no AWS Lambda sem exigir dependências adicionais. Para configurá-lo, modifique o Dockerfile do projeto conforme mostrado abaixo:
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" .
Modifique o código do manipulador de funções.
Este exemplo cria um código QR, carrega-o para um bucket S3 e lê o código QR recém-gerado.
O caminho do arquivo é especificado no diretório IronQrNuget, com um identificador globalmente único (GUID) usado como nome do arquivo. O método Write gera o código QR com base no valor fornecido, e o array de bytes JPG resultante é então passado para o método Read para leitura do código QR. Isso demonstra que essa função AWS Lambda é capaz de ler códigos 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);
/// <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(ByVal 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 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 jpgBytes() As Byte) As Task
Using memoryStream As New MemoryStream(jpgBytes)
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 NamespaceImports 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(ByVal 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 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 jpgBytes() As Byte) As Task
Using memoryStream As New MemoryStream(jpgBytes)
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 NamespaceAumentar a memória e o tempo limite
A alocação de memória para a função Lambda depende do tamanho dos documentos e do número de documentos processados simultaneamente. Como ponto de partida, defina a memória para 512 MB e o tempo limite para 300 segundos no aws-lambda-tools-defaults.json.
"function-memory-size" : 512,
"function-timeout" : 300
Se a memória for insuficiente, o programa exibirá o erro: 'Runtime exited with error: signal: killed.' Aumentar a quantidade de memória disponível pode ajudar a resolver esse problema. Para mais orientações, consulte o artigo de solução de problemas: AWS Lambda - Runtime Exited Signal: Killed.
Publicar
Para publicar no Visual Studio, basta clicar com o botão direito do mouse no projeto e escolher "Publicar no AWS Lambda...". Em seguida, configure as opções necessárias. Para mais informações, visite o site da AWS.
Experimente!
Você pode ativar a função Lambda através do console Lambda ou através do Visual Studio.
Perguntas frequentes
Como faço para configurar o IronQR no AWS Lambda?
Para configurar o IronQR no AWS Lambda, você precisa criar um projeto containerizado no Visual Studio, adicionar a biblioteca IronQR, configurar dependências, modificar o Dockerfile e implantar a função com configurações adequadas de memória e tempo de espera.
Quais são os pré-requisitos para usar o IronQR no AWS Lambda?
Você precisa do Visual Studio, AWS Toolkit para Visual Studio, o pacote AWSSDK.S3 para interação com o bucket S3, e a biblioteca IronQR.
O IronQR pode ler e escrever códigos QR diretamente em um bucket S3?
Sim, o IronQR pode ser configurado para ler e escrever códigos QR diretamente em um bucket S3 no AWS Lambda.
Como aumento as configurações de memória e tempo de espera para o IronQR no AWS Lambda?
Você pode aumentar as configurações de memória e tempo de espera ajustando os campos 'function-memory-size' e 'function-timeout' no arquivo aws-lambda-tools-defaults.json.
Como a biblioteca IronQR é integrada em um projeto containerizado .NET 8?
O IronQR é integrado adicionando a biblioteca ao projeto, modificando o Dockerfile e configurando o FunctionHandler para criar e ler códigos QR usando o IronQR.
O que devo fazer se a função Lambda ficar sem memória?
Se a função ficar sem memória, tente aumentar a configuração de alocação de memória no arquivo aws-lambda-tools-defaults.json e garanta que tenha recursos suficientes para operar eficientemente.
Como faço para implantar uma função AWS Lambda com IronQR?
Implante a função configurando o projeto para AWS Lambda, aumentando as configurações de memória e tempo de espera, se necessário, e usando o Visual Studio para publicar o projeto no AWS Lambda.
É necessário configuração adicional para o IronQR funcionar no AWS Lambda?
Nenhuma dependência adicional é necessária para o IronQR funcionar no AWS Lambda quando se usa .NET 8, além da configuração padrão do AWS.
O que é necessário para publicar um projeto com IronQR para o AWS Lambda no Visual Studio?
Para publicar, clique com o botão direito do mouse no projeto, selecione 'Publicar no AWS Lambda...' e configure as configurações necessárias no diálogo de publicação.
Como posso testar a função Lambda implantada usando o IronQR?
Você pode ativar e testar a função Lambda através do console do AWS Lambda ou diretamente do Visual Studio após a implantação.
Curtis Chau é bacharel em Ciência da Computação (Universidade Carleton) e se especializa em desenvolvimento front-end, com experiência em Node.js, TypeScript, JavaScript e React. Apaixonado por criar interfaces de usuário intuitivas e esteticamente agradáveis, Curtis gosta de trabalhar com frameworks modernos e criar manuais bem estruturados e visualmente atraentes.