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.
This technology is considered 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. For a full list of possible statuses, check our FAQ entry. |
Requisitos previos
To complete this guide, you need:
-
Roughly 30 minutes
-
An IDE
-
JDK 17+ installed with
JAVA_HOME
configured appropriately -
Apache Maven 3.9.9
-
Optionally the Quarkus CLI if you want to use it
-
Optionally Mandrel or GraalVM installed and configured appropriately if you want to build a native executable (or Docker if you use a native container build)
-
Lea sobre los fundamentos de Funqy. Esta es una lectura corta!
-
AWS SAM CLI, para pruebas locales
Funqy AWS Lambdas build off of our Quarkus AWS Lambda support. |
Instalación de los bits de AWS
Instalar todos los bits de AWS es probablemente lo más difícil de esta guía. Asegúrate de seguir todos los pasos para instalar AWS CLI.
El inicio rápido
Clone el repositorio Git: git clone https://github.com/quarkusio/quarkus-quickstarts.git
o descargue un archivo.
The solution is located in the funqy-amazon-lambda-quickstart
directory.
El 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.
Implementar en AWS Lambda Java Runtime
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.
Construir y desplegar
Build the project using Maven:
quarkus build
./mvnw install
Esto compilará y empaquetará su código.
Crear un rol de ejecución
Consulte la Guía de inicio para implementar un lambda con AWS CLI. Específicamente, asegúrese de haber creado un Execution Role
. Tendrá que definir una variable de entorno LAMBDA_ROLE_ARN
en su perfil o ventana de consola, Alternativamente, puede editar el script manage.sh
que es generado por la compilación y poner el valor del rol directamente allí:
LAMBDA_ROLE_ARN="arn:aws:iam::1234567890:role/lambda-role"
Archivos extra generados por la compilación
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
- archivo de despliegue de lambda -
manage.sh
- envoltura alrededor de las llamadas aws lambda cli -
bootstrap-example.sh
- ejemplo de secuencia de comandos de arranque para las implantaciones nativas -
sam.jvm.yaml
- (opcional) para su uso con sam cli y pruebas locales -
sam.native.yaml
- (opcional) para su uso con sam cli y pruebas locales nativas
Crear la función
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
admite cuatro operaciones: create
, delete
, update
, y invoke
.
Para verificar su configuración, que tiene la CLI de AWS instalada, ha ejecutado aws configure para las claves de acceso de AWS y ha configurado la variable de entorno LAMBDA_ROLE_ARN (como se ha descrito anteriormente), ejecute manage.sh sin ningún parámetro. Se imprimirá una declaración de uso para guiarte en consecuencia.
|
Para ver la declaración usage
, y validar la configuración de AWS:
sh target/manage.sh
Puede crear su función utilizando el siguiente comando, create
:
sh target/manage.sh create
o si no tiene LAMBDA_ROLE_ARN
ya definido en este 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.
|
Si hay algún problema en la creación de la función, debe borrarla con la función delete
antes de volver a ejecutar el comando create
.
sh target/manage.sh delete
Los comandos también pueden apilarse:
sh target/manage.sh delete create
Invoke the function
Utilice el comando invoke
para invocar su función.
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
Si está trabajando con su construcción de imagen nativa, simplemente reemplace el nombre de la plantilla con la versión 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
Implementación en el tiempo de ejecución personalizado (nativo) de 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:
quarkus build --native
./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.
|
quarkus build --native --no-tests -Dquarkus.native.container-build=true
# The --no-tests flag is required only on Windows and macOS.
./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.
Las instrucciones son exactamente las mismas que las anteriores con un cambio: tendrá que añadir native
como primer parámetro del script manage.sh
:
sh target/manage.sh native create
Como en el caso anterior, los comandos se pueden apilar. El único requisito es que native
sea el primer parámetro si desea trabajar con construcciones de imágenes nativas. El script se encargará del resto de los detalles necesarios para gestionar sus despliegues de funciones de imagen 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.
Una cosa a tener en cuenta sobre el comando de creación para nativos es que la llamada a aws lambda create-function
debe establecer una variable de entorno específica:
--environment 'Variables={DISABLE_SIGNAL_HANDLERS=true}'
Examinar el 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());
}
}
Pruebas con la CLI de SAM
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.
Se ha generado una plantilla de inicio para los modos de ejecución JVM y 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
La imagen nativa también puede probarse localmente utilizando la plantilla sam.native.yaml
:
sam local invoke --template target/sam.native.yaml --event payload.json
Modificación de 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 los archivos y directorios que crees bajo tu directorio zip se incluirán dentro de function.zip
Guión personalizado de 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.
El ejecutable nativo debe ser referenciado como runner si incluye un script personalizado de bootstrap .
|
La extensión genera un script de ejemplo dentro de target/bootstrap-example.sh
.