The English version of quarkus.io is the official project site. Translated sites are community supported on a best-effort basis.

Funqy AWS Lambda Binding

The guide walks through quickstart code to show you how you can deploy Funqy functions to AWS Lambda.

Funqy functions can be deployed using the AWS Lambda Java Runtime, or you can build a native executable and use Lambda Custom Runtime if you want a smaller memory footprint and faster cold boot startup time.

Essa tecnologia é considerada preview.

In preview, backward compatibility and presence in the ecosystem is not guaranteed. Specific improvements might require changing configuration or APIs, and plans to become stable are under way. Feedback is welcome on our mailing list or as issues in our GitHub issue tracker.

Para obter uma lista completa de possíveis status, consulte nosso FAQ.

Pré-requisitos

Para concluir este guia, você precisa:

  • Mais ou menos 30 minutes

  • Um IDE

  • JDK 17+ installed with JAVA_HOME configured appropriately

  • Apache Maven 3.9.6

  • Opcionalmente, o Quarkus CLI se você quiser usá-lo

  • Opcionalmente, Mandrel ou GraalVM instalado e configurado apropriadamente se você quiser criar um executável nativo (ou Docker se você usar uma compilação de contêiner nativo)

  • Read about Funqy Basics. This is a short read!

  • Uma conta Amazon AWS

  • CLI da AWS

  • AWS SAM CLI, para testes locais

Funqy AWS Lambdas build off of our Quarkus AWS Lambda support.

Instalando os componentes AWS

A instalação de todos os bits da AWS é provavelmente a parte mais difícil deste guia. Certifique-se de seguir todas as etapas para instalar a AWS CLI.

The Quickstart

Clone o repositório Git: git clone https://github.com/quarkusio/quarkus-quickstarts.git, ou baixe um arquivo.

The solution is located in the funqy-amazon-lambda-quickstart directory.

O Código

There is nothing special about the code and more importantly nothing AWS specific. Funqy functions can be deployed to many environments and AWS Lambda is one of them. The Java code is actually the same exact code as the funqy-http-quickstart.

Choose Your Function

Only one Funqy function can be exported per AWS Lambda deployment. If you have multiple functions defined within your project, then you will need to choose the function within your Quarkus application.properties:

quarkus.funqy.export=greet

You can see how the quickstart has done it within its own application.properties.

Alternatively, you can set the QUARKUS_FUNQY_EXPORT environment variable when you create the AWS Lambda using the aws cli.

Implantar no runtime Java da AWS Lambda

There are a few steps to get your Funqy function running on AWS Lambda. The quickstart maven project generates a helpful script to create, update, delete, and invoke your functions for pure Java and native deployments. This script is generated at build time.

Build e Deploy

Build the project using Maven:

CLI
quarkus build
Maven
./mvnw install

Isto irá compilar e empacotar o seu código.

Criar uma função de execução

Consulte o Guia de Introdução para implantar um lambda com a AWS CLI. Especificamente, certifique-se de ter criado um Execution Role. Será necessário definir uma variável de ambiente LAMBDA_ROLE_ARN no seu perfil ou na janela do console. Como alternativa, você pode editar o script manage.sh gerado pela compilação e colocar o valor da função diretamente lá:

LAMBDA_ROLE_ARN="arn:aws:iam::1234567890:role/lambda-role"

Arquivos extras gerados pela compilação

After you run the build, there are a few extra files generated by the quarkus-funqy-amazon-lambda extension. These files are in the build directory: target/ for maven, build/ for gradle.

  • function.zip - arquivo de deployment lambda

  • manage.sh - script para chamadas do lambda através da AWS CLI

  • bootstrap-example.sh - exemplo de script de inicialização para implementações nativas

  • sam.jvm.yaml - (opcional) para utilização com SAM CLI e testes locais

  • sam.native.yaml - (opcional) para utilização com SAM CLI e testes locais nativos

Criar a função

The target/manage.sh script is for managing your Funqy function using the AWS Lambda Java runtime. This script is provided only for your convenience. Examine the output of the manage.sh script if you want to learn what aws commands are executed to create, delete, and update your functions.

manage.sh suporta quatro operações: create , delete , update , e invoke.

Para verificar a configuração, se você tem a AWS CLI instalada, se executou o aws configure para as chaves de acesso da AWS, e configurou a variável de ambiente LAMBDA_ROLE_ARN (conforme descrito acima), execute manage.sh sem nenhum parâmetro. Uma declaração de uso será impressa para orientá-lo adequadamente.

Para ver a declaração usage e validar a configuração da AWS:

sh target/manage.sh

Pode create a sua função utilizando o seguinte comando:

sh target/manage.sh create

ou se não tiver LAMBDA_ROLE_ARN já definido neste shell:

LAMBDA_ROLE_ARN="arn:aws:iam::1234567890:role/lambda-role" sh target/manage.sh create
Do not change the handler switch. This must be hardcoded to io.quarkus.funqy.lambda.FunqyStreamHandler::handleRequest. This special handler is Funqy’s integration point with AWS Lambda.

Se houver algum problema na criação da função, você deverá excluí-la com a função delete antes de executar novamente o comando create.

sh target/manage.sh delete

Os comandos também podem ser empilhados:

sh target/manage.sh delete create

Invoke the function

Utilize o comando invoke para invocar a sua função.

sh target/manage.sh invoke

The example function takes input passed in via the --payload switch which points to a json file in the root directory of the project.

The function can also be invoked locally with the SAM CLI like this:

sam local invoke --template target/sam.jvm.yaml --event payload.json

Se estiver a trabalhar com a sua compilação de imagem nativa, basta substituir o nome do modelo pela versão nativa:

sam local invoke --template target/sam.native.yaml --event payload.json

Update the function

You can update the Java code as you see fit. Once you’ve rebuilt, you can redeploy your function by executing the update command.

sh target/manage.sh update

Implantar no runtime personalizado (nativo) do AWS Lambda

If you want a lower memory footprint and faster initialization times for your Funqy function, you can compile your Java code to a native executable. Just make sure to rebuild your project with the -Dnative switch.

For Linux hosts execute:

CLI
quarkus build --native
Maven
./mvnw install -Dnative
If you are building on a non-Linux system, you will need to also pass in a property instructing Quarkus to use a Docker build as Amazon Lambda requires Linux binaries. You can do this by passing this property to your build: -Dnative-image.docker-build=true. This requires you to have Docker installed locally, however.
CLI
quarkus build --native --no-tests -Dquarkus.native.container-build=true
# The --no-tests flag is required only on Windows and macOS.
Maven
./mvnw install -Dnative -DskipTests -Dquarkus.native.container-build=true

Either of these commands will compile and create a native executable. It also generates a zip file target/function.zip. This zip file contains your native executable image renamed to bootstrap. This is a requirement of the AWS Lambda Custom (Provided) Runtime.

As instruções aqui são exatamente como acima, com uma alteração: você precisará adicionar native como o primeiro parâmetro do script manage.sh:

sh target/manage.sh native create

Como acima, os comandos podem ser empilhados. A única exigência é que native seja o primeiro parâmetro, caso deseje trabalhar com compilações de imagens nativas. O script cuidará dos detalhes necessários para gerenciar suas implementações de funções de imagem nativa.

Examine the output of the manage.sh script if you want to learn what aws commands are executed to create, delete, and update your functions.

Um aspecto a ser observado sobre o comando create para nativo é que a chamada aws lambda create-function deve definir uma variável de ambiente específica:

--environment 'Variables={DISABLE_SIGNAL_HANDLERS=true}'

Examinando o POM

There is nothing special about the POM other than the inclusion of the quarkus-funqy-amazon-lambda extension as a dependency. The extension automatically generates everything you might need for your lambda deployment.

Integration Testing

Funqy AWS Lambda support leverages the Quarkus AWS Lambda test framework so that you can unit tests your Funqy functions. This is true for both JVM and native modes. This test framework provides similar functionality to the SAM CLI, without the overhead of Docker.

If you open up FunqyTest.java you’ll see that the test replicates the AWS execution environment.

package org.acme.funqy;

import io.quarkus.amazon.lambda.test.LambdaClient;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

@QuarkusTest
public class FunqyTest {
    @Test
    public void testSimpleLambdaSuccess() throws Exception {
        Friend friend = new Friend("Bill");
        Greeting out = LambdaClient.invoke(Greeting.class, friend);
        Assertions.assertEquals("Hello Bill", out.getMessage());
    }
}

Testes com a SAM CLI

The AWS SAM CLI allows you to run your functions locally on your laptop in a simulated Lambda environment. This requires docker to be installed. This is an optional approach should you choose to take advantage of it. Otherwise, the Quarkus JUnit integration should be sufficient for most of your needs.

Foi gerado um modelo inicial para os modos de execução JVM e nativo.

Run the following SAM CLI command to locally test your function, passing the appropriate SAM template. The event parameter takes any JSON file, in this case the sample payload.json.

sam local invoke --template target/sam.jvm.yaml --event payload.json

A imagem nativa também pode ser testada localmente utilizando o modelo sam.native.yaml:

sam local invoke --template target/sam.native.yaml --event payload.json

Modificar function.zip

There are times when you may have to add additional entries to the function.zip lambda deployment that is generated by the build. To do this, create a zip.jvm or zip.native directory within src/main. Create zip.jvm/ if you are doing a pure Java. zip.native/ if you are doing a native deployment.

Todos os ficheiros e diretórios que criar no seu diretório zip serão incluídos no function.zip

Script personalizado bootstrap

There are times you may want to set specific system properties or other arguments when lambda invokes your native Funqy deployment. If you include a bootstrap script file within zip.native, the Funqy extension will automatically rename the executable to runner within function.zip and set the unix mode of the bootstrap script to executable.

O executável nativo tem de ser referenciado como runner se incluir um script bootstrap personalizado.

A extensão gera um script de exemplo em target/bootstrap-example.sh.

Conteúdo Relacionado