AWS Lambda
`quarkus-amazon-lambda`扩展使您能够使用 Quarkus 构建 AWS Lambdas。您的 lambdas 可以根据需要使用来自 CDI 或 Spring 的注入注释和其他 Quarkus 功能。
The quarkus-amazon-lambda
extension allows you to use Quarkus to build your AWS Lambdas.
Your lambdas can use injection annotations from CDI or Spring and other Quarkus facilities as you need them.
Quarkus lambdas 可以使用 Amazon Java Runtime 进行部署,或者您可以构建一个本地可执行程序并使用 Amazon 的自定义运行时,如果您想要一个占用更少内存且冷启动时间更快的程序。
Quarkus lambdas can be deployed using the Amazon Java Runtime, or you can build a native executable and use Amazon’s Custom Runtime if you want a smaller memory footprint and faster cold boot startup time.
Quarkus 与 lambdas 的集成还支持 Quarkus 的实时编码开发周期。您可以在开发或测试模式下启动您的 Quarkus lambda 项目,并在您的项目中进行实时编码。
Quarkus’s integration with lambdas also supports Quarkus’s Live Coding development cycle. You can bring up your Quarkus lambda project in dev or test mode and code on your project live.
Prerequisites
include::{includes}/prerequisites.adoc[]* An Amazon AWS account* AWS CLI* AWS SAM CLI 适用于本地测试
Unresolved directive in aws-lambda.adoc - include::{includes}/prerequisites.adoc[] * An Amazon AWS account * AWS CLI * AWS SAM CLI, for local testing
对于 Gradle 项目,请参阅 see below,或进一步参考 Gradle setup page 中的指南。 |
For Gradle projects please gradle, or for further reference consult the guide in the Gradle setup page. |
Getting Started
本指南引导你使用 maven 原型生成 Java 项目示例,并将它部署到 AWS。
This guide walks you through generating an example Java project via a maven archetype and deploying it to AWS.
Installing AWS bits
安装所有 AWS 位可能是这个指南最困难的部分。请务必遵循所有步骤来安装 AWS CLI。
Installing all the AWS bits is probably the most difficult thing about this guide. Make sure that you follow all the steps for installing AWS CLI.
Creating the Maven Deployment Project
使用 Maven 原型创建 Quarkus AWS Lambda maven 项目。
Create the Quarkus AWS Lambda maven project using our Maven Archetype.
mvn archetype:generate \
-DarchetypeGroupId=io.quarkus \
-DarchetypeArtifactId=quarkus-amazon-lambda-archetype \
-DarchetypeVersion={quarkus-version}
如果你希望使用 Gradle,你可以快速轻松地通过 code.quarkus.io 将 If you prefer to use Gradle, you can quickly and easily generate a Gradle project via code.quarkus.io
adding the 将 build.gradle、gradle.properties 和 settings.gradle 复制到上述生成的 Maven 原型项目,以便遵循本指南。 Copy the build.gradle, gradle.properties and settings.gradle into the above-generated Maven archetype project, to follow along with this guide. 执行:gradle wrapper 以设置 gradle wrapper(推荐)。 Execute: gradle wrapper to set up the gradle wrapper (recommended). 有关 Gradle 的完整详细信息,请参阅以下的 Gradle build 部分。 For full Gradle details, see the gradle section below. |
Choose Your Lambda
quarkus-amazon-lambda
扩展将扫描你的项目,寻找直接实现 Amazon RequestHandler<?, ?>
或 RequestStreamHandler
的接口的类。它必须找到一个实现该接口的类,否则它将引发构建时故障。如果它找到多个处理程序类,也将引发构建时异常。
The quarkus-amazon-lambda
extension scans your project for a class that directly implements the Amazon RequestHandler<?, ?>
or RequestStreamHandler
interface.
It must find a class in your project that implements this interface, or it will throw a build time failure.
If it finds more than one handler class, a build time exception will also be thrown.
然而,有时你可能有几个共享代码的关联 lambda,而创建多个 maven 模块只是你不想做的开销。quarkus-amazon-lambda
扩展允许你在一个项目中捆绑多个 lambda,并使用配置或环境变量来选择你希望部署的处理程序。
Sometimes, though, you might have a few related lambdas that share code and creating multiple maven modules is just
an overhead you don’t want to do. The quarkus-amazon-lambda
extension allows you to bundle multiple lambdas in one
project and use configuration or an environment variable to pick the handler you want to deploy.
生成项目在其中包含三个 lambda。两个实现 RequestHandler<?, ?>
接口,一个实现 RequestStreamHandler
接口。一个正在使用,两个未被使用。如果你打开 src/main/resources/application.properties
,你将看到:
The generated project has three lambdas within it. Two that implement the RequestHandler<?, ?>
interface, and one that implements the RequestStreamHandler
interface. One that is used and two that are unused. If you open up
src/main/resources/application.properties
you’ll see this:
quarkus.lambda.handler=test
quarkus.lambda.handler
属性告诉 Quarkus 部署哪个 lambda 处理程序。这也可用环境变量覆盖。
The quarkus.lambda.handler
property tells Quarkus which lambda handler to deploy. This can be overridden
with an environment variable too.
如果你查看项目中生成的三个处理程序类,你将看到它们被 @Named
不同地实现。
If you look at the three generated handler classes in the project, you’ll see that they are @Named
differently.
@Named("test")
public class TestLambda implements RequestHandler<InputObject, OutputObject> {
}
@Named("unused")
public class UnusedLambda implements RequestHandler<InputObject, OutputObject> {
}
@Named("stream")
public class StreamLambda implements RequestStreamHandler {
}
处理程序类的 CDI 名称必须与 quarkus.lambda.handler
中指定的值匹配。
The CDI name of the handler class must match the value specified within the quarkus.lambda.handler
property.
Deploy to AWS Lambda Java Runtime
在你 AWS 上运行 lambda 有一些步骤。生成 maven 项目包含一个帮助脚本,可为纯 Java 和本机部署创建、更新、删除和调用你的 lambdas。
There are a few steps to get your lambda running on AWS. The generated maven project contains a helpful script to create, update, delete, and invoke your lambdas for pure Java and native deployments.
Build and Deploy
构建项目:
Build the project:
Unresolved directive in aws-lambda.adoc - include::{includes}/devtools/build.adoc[]
这将编译和打包你的代码。
This will compile and package your code.
Create an Execution Role
查看 Getting Started Guide 以使用 AWS CLI 部署 Lambda。具体来说,请确保你已经创建了一个 Execution Role
。你将需要在你的个人资料或控制台窗口中定义一个 LAMBDA_ROLE_ARN
环境变量,或者,你可以在构建生成的 manage.sh
脚本中编辑并将角色值直接放在其中:
View the Getting Started Guide for deploying
a lambda with AWS CLI. Specifically, make sure you have created an Execution Role
. You will need to define
a LAMBDA_ROLE_ARN
environment variable in your profile or console window, Alternatively, you can edit
the manage.sh
script that is generated by the build and put the role value directly there:
LAMBDA_ROLE_ARN="arn:aws:iam::1234567890:role/lambda-role"
Extra Build Generated Files
在你运行构建之后,quarkus-amazon-lambda
扩展将生成一些额外的文件。这些文件位于构建目录中: maven 的 target/
、gradle 的 build/
。
After you run the build, there are a few extra files generated by the quarkus-amazon-lambda
extension. These files
are in the build directory: target/
for maven, build/
for gradle.
-
function.zip
- lambda deployment file -
manage.sh
- wrapper around aws lambda cli calls -
bootstrap-example.sh
- example bootstrap script for native deployments -
sam.jvm.yaml
- (optional) for use with sam cli and local testing -
sam.native.yaml
- (optional) for use with sam cli and native local testing
Create the function
target/manage.sh
脚本用于使用 AWS Lambda Java 运行时来管理你的 lambda。此脚本只为你方便提供。查看 manage.sh
脚本的输出,如果你想了解为了创建、删除和更新你的 lambdas 而执行了哪些 AWS 命令。
The target/manage.sh
script is for managing your lambda 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 lambdas.
manage.sh
支持四种操作:create
、delete
、update`和 `invoke
。
manage.sh
supports four operation: create
, delete
, update
, and invoke
.
为了验证你的设置,你已经安装了 AWS CLI,执行了 AWS 访问密钥的 aws configure,并且设置了 |
To verify your setup, that you have the AWS CLI installed, executed aws configure for the AWS access keys,
and set up the |
如果使用 Gradle,则 |
If using Gradle, the path to the binaries in the |
以下载 usage
陈述,以及验证 AWS 配置:
To see the usage
statement, and validate AWS configuration:
sh target/manage.sh
你可以使用以下命令 create
你的函数:
You can create
your function using the following command:
sh target/manage.sh create
或者,如果你尚未在这个 shell 中定义 LAMBDA_ROLE_ARN
:
or if you do not have LAMBDA_ROLE_ARN
already defined in this shell:
LAMBDA_ROLE_ARN="arn:aws:iam::1234567890:role/lambda-role" sh target/manage.sh create
不要更改处理程序开关。此项必须硬编码为 io.quarkus.amazon.lambda.runtime.QuarkusStreamHandler::handleRequest
。此处理程序引导 Quarkus 并包装您的实际处理程序,以便执行注入。
Do not change the handler switch. This must be hardcoded to io.quarkus.amazon.lambda.runtime.QuarkusStreamHandler::handleRequest
. This
handler bootstraps Quarkus and wraps your actual handler so that injection can be performed.
如果有任何问题在创建函数时发生,你需要使用 delete
删除它,然后重新运行 create
命令。
If there are any problems creating the function, you must delete it with the delete
function before re-running
the create
command.
sh target/manage.sh delete
命令也可以被叠加:
Commands may also be stacked:
sh target/manage.sh delete create
Invoke the Lambda
使用 invoke
命令来调用你的函数。
Use the invoke
command to invoke your function.
sh target/manage.sh invoke
示例 lambda 接受通过 `--payload`传入的输入开关指向项目根目录中的 json 文件。
The example lambda takes input passed in via the --payload
switch which points to a json file
in the root directory of the project.
还可以使用 SAM CLI 这样在本地调用 lambda:
The lambda can also be invoked locally with the SAM CLI like this:
sam local invoke --template target/sam.jvm.yaml --event payload.json
如果使用的是本机映像构建,则只需将模板名称替换为本机版本:
If you are working with your native image build, simply replace the template name with the native version:
sam local invoke --template target/sam.native.yaml --event payload.json
Update the Lambda
您可以根据需要更新 Java 代码。重新编译后,您可以通过执行 `update`命令重新部署您的 lambda。
You can update the Java code as you see fit. Once you’ve rebuilt, you can redeploy your lambda by executing the
update
command.
sh target/manage.sh update
Deploy to AWS Lambda Custom (native) Runtime
如果您希望为 lambda 减小内存占用并加快初始化时间,您可以将 Java 代码编译为原生可执行文件。确保使用 `-Dnative`开关重新编译您的项目。
If you want a lower memory footprint and faster initialization times for your lambda, you can compile your Java
code to a native executable. Just make sure to rebuild your project with the -Dnative
switch.
对于 Linux 主机,执行:
For Linux hosts, execute:
Unresolved directive in aws-lambda.adoc - include::{includes}/devtools/build-native.adoc[]
如果您在非 Linux 系统上构建,您还需要传递一个属性指示 Quarkus 使用 docker 构建,因为 AmazonLambda 要求 linux 二进制文件。您可以通过将此属性传递给您的构建来实现: |
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:
|
Unresolved directive in aws-lambda.adoc - include::{includes}/devtools/build-native-container.adoc[]
上述任何命令都会编译并创建一个原生可执行镜像。它还生成一个 zip 文件 target/function.zip
。此 zip 文件包含已重命名为 `bootstrap`的原生可执行镜像。这是 AWS LambdaCustom(提供)运行时的要求。
Either of these commands will compile and create a native executable image. 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.
此处的说明与上面完全相同,只有一处更改:您需要将 native
添加为 manage.sh
脚本的第一个参数:
The instructions here are exactly as above with one change: you’ll need to add native
as the first parameter to the
manage.sh
script:
sh target/manage.sh native create
与上面一样,可以堆叠命令。唯一的要求是,如果您希望使用本机映像构建,则第一个参数必须是 native
。该脚本将负责管理本机映像函数部署所需的其余详细信息。
As above, commands can be stacked. The only requirement is that native
be the first parameter should you wish
to work with native image builds. The script will take care of the rest of the details necessary to manage your native
image function deployments.
如果您想了解执行哪些 aws 命令来创建、删除和更新您的 lambdas,请检查 `manage.sh`脚本的输出。
Examine the output of the manage.sh
script if you want to learn what aws commands are executed
to create, delete, and update your lambdas.
关于本机创建命令要注意的一件事是 aws lambda create-function
调用必须设置一个特定的环境变量:
One thing to note about the create command for native is that the aws lambda create-function
call must set a specific environment variable:
--environment 'Variables={DISABLE_SIGNAL_HANDLERS=true}'
Examine the POM and Gradle build
POM 没有什么特别之处,除了包含 `quarkus-amazon-lambda`扩展作为依赖关系。此扩展自动生成您用于 lambda 部署所需的一切。
There is nothing special about the POM other than the inclusion of the quarkus-amazon-lambda
extension
as a dependency. The extension automatically generates everything you might need for your lambda deployment.
在此扩展的早期版本中,您必须设置您的 pom 或 gradle 来压缩您的可执行文件以便进行原生部署,但这现在已不是必需的。 |
In previous versions of this extension, you had to set up your pom or gradle to zip up your executable for native deployments, but this is not the case anymore. |
Gradle build
同样,对于 Gradle 项目,您也只需要添加 `quarkus-amazon-lambda`依赖关系。此扩展自动生成您用于 lambda 部署所需的一切。
Similarly, for Gradle projects, you also just have to add the quarkus-amazon-lambda
dependency. The extension automatically generates everything you might need
for your lambda deployment.
示例 Gradle 依赖关系:
Example Gradle dependencies:
dependencies {
implementation enforcedPlatform("${quarkusPlatformGroupId}:${quarkusPlatformArtifactId}:${quarkusPlatformVersion}")
implementation 'io.quarkus:quarkus-resteasy'
implementation 'io.quarkus:quarkus-amazon-lambda'
testImplementation 'io.quarkus:quarkus-junit5'
testImplementation 'io.rest-assured:rest-assured'
}
Live Coding and Unit/Integration Testing
为了在开发环境中尽可能镜像 AWS Lambda 环境,Quarkus AWS Lambda 扩展在 Quarkus Dev 和测试模式下启动一个模拟 AWS Lambda 事件服务器。此模拟事件服务器模拟一个真实的 AWS Lambda 环境。
To mirror the AWS Lambda environment as closely as possible in a dev environment, the Quarkus AWS Lambda extension boots up a mock AWS Lambda event server in Quarkus Dev and Test mode. This mock event server simulates a true AWS Lambda environment.
在 Quarkus Dev 模式下运行时,您可以通过对 `http://localhost:8080`执行 HTTP POST 来向其提供事件。模拟事件服务器将接收事件,然后调用您的 lambda。您可以在 lambda 上执行实时编码,并且在您进行的下次调用中,更改将自动重新编译且可用。以下是示例:
While running in Quarkus Dev Mode, you can feed events to it by doing an HTTP POST to http://localhost:8080
.
The mock event server will receive the events and your lambda will be invoked. You can perform live coding on your lambda
and changes will automatically be recompiled and available the next invocation you make. Here’s an example:
Unresolved directive in aws-lambda.adoc - include::{includes}/devtools/dev.adoc[]
$ curl -d "{\"name\":\"John\"}" -X POST http://localhost:8080
对于您的单元测试,您还可以使用所需的任何 HTTP 客户端来调用模拟事件服务器。以下是使用 rest-assured 的示例。Quarkus 启动一个单独的模拟事件服务器,端口为 8081。Quarkus 会自动将 Rest Assured 的默认端口设置为 8081,因此您可以调用此终结点。
For your unit tests, you can also invoke on the mock event server using any HTTP client you want. Here’s an example using rest-assured. Quarkus starts up a separate Mock Event server under port 8081. The default port for Rest Assured is automatically set to 8081 by Quarkus, so you can invoke on this endpoint.
import org.junit.jupiter.api.Test;
import io.quarkus.test.junit.QuarkusTest;
import static io.restassured.RestAssured.given;
import static org.hamcrest.CoreMatchers.containsString;
@QuarkusTest
public class LambdaHandlerTest {
@Test
public void testSimpleLambdaSuccess() throws Exception {
Person in = new Person();
in.setName("Stu");
given()
.contentType("application/json")
.accept("application/json")
.body(in)
.when()
.post()
.then()
.statusCode(200)
.body(containsString("Hello Stu"));
}
}
模拟事件服务器还为 @QuarkusIntegrationTest
测试启动,因此也将适用于原生二进制文件。所有这些都提供了类似于 SAM CLI 本地测试的功能,但无需 Docker 的开销。
The mock event server is also started for @QuarkusIntegrationTest
tests so will work
with native binaries too. All this provides similar functionality to the SAM CLI local testing, without the overhead of Docker.
最后,如果计算机上没有端口 8080 或端口 8081,您可以使用 application.properties 修改开发和测试模式端口
Finally, if port 8080 or port 8081 is not available on your computer, you can modify the dev and test mode ports with application.properties
quarkus.lambda.mock-event-server.dev-port=8082
quarkus.lambda.mock-event-server.test-port=8083
端口值为零将导致随机分配端口。
A port value of zero will result in a randomly assigned port.
关闭模拟事件服务器:
To turn off the mock event server:
quarkus.lambda.mock-event-server.enabled=false
Testing with the SAM CLI
如果您不想使用模拟事件服务器,您可以使用 SAM CLI 来测试您的 lambdas。
If you do not want to use the mock event server, you can test your lambdas with SAM CLI.
AWS SAM CLI允许您在笔记本电脑上以模拟 Lambda 环境在本地运行您的 lambdas。此项要求安装了 docker。这是一个可选方法,如果您选择,可以利用它。否则,Quarkus JUnit 集成应该足以满足您的大部分需求。
The AWS SAM CLI allows you to run your lambdas 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.
已为 JVM 和本机执行模式生成了一个 starter 模板。
A starter template has been generated for both JVM and native execution modes.
运行以下 SAM CLI 命令来在本地测试您的 lambda 函数,传递适当的 SAM template
。event`参数接受任何 JSON 文件,在此例中是示例 `payload.json
。
Run the following SAM CLI command to locally test your lambda function, passing the appropriate SAM template
.
The event
parameter takes any JSON file, in this case the sample payload.json
.
如果使用 Gradle,YAML 模板中二进制文件的路径必须从 |
If using Gradle, the path to the binaries in the YAML templates must be changed from |
sam local invoke --template target/sam.jvm.yaml --event payload.json
还可以使用 sam.native.yaml
模板在本地测试本机映像:
The native image can also be locally tested using the sam.native.yaml
template:
sam local invoke --template target/sam.native.yaml --event payload.json
Modifying function.zip
有时,您可能需要对由构建生成的 function.zip
lambda 部署添加一些附加内容。要执行此操作,请在 src/main
中创建一个 zip.jvm
或 zip.native
目录。如果您正在执行纯 Java lambda,则创建 zip.jvm/
。如果您正在执行本机部署,则创建 zip.native/
。
There are times when you may have to add some additions 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 lambda. zip.native/
if you are doing a native deployment.
您在 zip 目录下创建的任何文件和目录都将包含在 function.zip
中
Any you files and directories you create under your zip directory will be included within function.zip
Custom bootstrap
script
有时,您可能希望在 lambda 调用您的本机 quarkus lambda 部署时设置特定的系统属性或其他参数。如果您在 zip.native
中包含一个 bootstrap
脚本文件,quarkus 扩展程序会自动将可执行文件重命名为 function.zip
中的 runner
,并将 bootstrap
脚本的 Unix 模式设置为可执行。
There are times you may want to set a specific system properties or other arguments when lambda invokes
your native quarkus lambda deployment. If you include a bootstrap
script file within
zip.native
, the quarkus extension will automatically rename the executable to runner
within
function.zip
and set the unix mode of the bootstrap
script to executable.
如果您包含自定义 |
The native executable must be referenced as |
该扩展将在 target/bootstrap-example.sh
中生成一个示例脚本来。
The extension generates an example script within target/bootstrap-example.sh
.
Tracing with AWS XRay and GraalVM
如果您正在构建本机镜像,并且希望在 lambda 中使用 AWS X-Ray Tracing,您需要将 quarkus-amazon-lambda-xray
包含到 pom 中作为依赖项。AWS X-Ray 库与 GraalVM 并不完全兼容,因此我们必须做一些集成工作才能使其正常运行。
If you are building native images, and want to use AWS X-Ray Tracing with your lambda
you will need to include quarkus-amazon-lambda-xray
as a dependency in your pom. The AWS X-Ray
library is not fully compatible with GraalVM, so we had to do some integration work to make this work.
此外,请记住在 cmd_create()
函数中启用 manage.sh
中的 AWS X-Ray 跟踪参数。这也可以在 AWS 管理控制台中设置。
In addition, remember to enable the AWS X-Ray tracing parameter in manage.sh
, in the cmd_create()
function. This can also be set in the AWS Management Console.
--tracing-config Mode=Active
对于 sam 模板文件,请将以下内容添加到 YAML 函数属性。
For the sam template files, add the following to the YAML function Properties.
Tracing: Active
AWS X-Ray 会将许多类添加到您的分发中,请确保至少使用 256MB 的 AWS Lambda 内存大小。这在 manage.sh
cmd_create()
中显式设置。虽然本机映像可能始终可以使用较低的内存设置,但建议保持相同设置,特别是为了帮助比较性能。
AWS X-Ray does add many classes to your distribution, do ensure you are using at least the 256MB AWS Lambda memory size.
This is explicitly set in manage.sh
cmd_create()
. Whilst the native image potentially can always use a lower memory setting, it would be recommended to keep the setting the same, especially to help compare performance.
Using HTTPS or SSL/TLS
如果您的代码执行了 HTTPS 调用(例如,对微服务,对 AWS 服务),您将需要向本机映像添加配置,因为 GraalVM 仅在显式声明时包含依赖项。默认情况下,Quarkus 会在隐式需要它的扩展程序上启用此功能。有关更多信息,请查阅 Quarkus SSL guide。
If your code makes HTTPS calls (e.g. to a microservice, to an AWS service), you will need to add configuration to the native image, as GraalVM will only include the dependencies when explicitly declared. Quarkus, by default enables this functionality on extensions that implicitly require it. For further information, please consult the Quarkus SSL guide
打开 src/main/resources/application.properties,并添加以下行以在您的本机映像中启用 SSL。
Open src/main/resources/application.properties and add the following line to enable SSL in your native image.
quarkus.ssl.native=true
Using the AWS Java SDK v2
Quarkus 现在有用于 DynamoDB、S3、SNS 和 SQS 的扩展程序(还有更多)。请查看 those guides 来了解如何使用各种 AWS 服务和 Quarkus,而不是像下面这样手动连接。 |
Quarkus now has extensions for DynamoDB, S3, SNS and SQS (more coming). Please check those guides on how to use the various AWS Services with Quarkus, as opposed to wiring manually like below. |
通过最少的集成,可以利用可以用来调用 SQS、SNS、S3 和 DynamoDB 等服务的 AWS Java SDK v2。
With minimal integration, it is possible to leverage the AWS Java SDK v2, which can be used to invoke services such as SQS, SNS, S3 and DynamoDB.
然而,对于本机映像,在同步模式下,由于 GraalVM 编译中的问题(目前),必须优先选择 URL 连接客户端而不是 Apache HTTP 客户端。
For native image, however, the URL Connection client must be preferred over the Apache HTTP Client when using synchronous mode, due to issues in the GraalVM compilation (at present).
在您的 Maven pom.xml
或 Gradle build.gradle
文件中将 quarkus-jaxb
添加为依赖项。
Add quarkus-jaxb
as a dependency in your Maven pom.xml
, or Gradle build.gradle
file.
您还必须强制用于 SQS、SNS、S3 等的 AWS 服务客户端使用 URL 连接客户端,该客户端通过 HTTPS 连接到 AWS 服务,因此包含 SSL 启用的属性,如上面 Using HTTPS or SSL/TLS 一节中所述。
You must also force your AWS service client for SQS, SNS, S3 et al., to use the URL Connection client, which connects to AWS services over HTTPS, hence the inclusion of the SSL enabled property, as described in the Using HTTPS or SSL/TLS section above.
// select the appropriate client, in this case SQS, and
// insert your region, instead of XXXX, which also improves startup time over the default client
client = SqsClient.builder().region(Region.XXXX).httpClient(software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient.builder().build()).build();
对于 Maven,请将以下内容添加到您的 pom.xml
。
For Maven, add the following to your pom.xml
.
<properties>
<aws.sdk2.version>2.10.69</aws.sdk2.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>bom</artifactId>
<version>${aws.sdk2.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>url-connection-client</artifactId>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>apache-client</artifactId>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<!-- sqs/sns/s3 etc -->
<artifactId>sqs</artifactId>
<exclusions>
<!-- exclude the apache-client and netty client -->
<exclusion>
<groupId>software.amazon.awssdk</groupId>
<artifactId>apache-client</artifactId>
</exclusion>
<exclusion>
<groupId>software.amazon.awssdk</groupId>
<artifactId>netty-nio-client</artifactId>
</exclusion>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>commons-logging-jboss-logging</artifactId>
</dependency>
</dependencies>
如果您看到 |
if you see |
Additional requirements for client SSL
本机可执行文件需要一些额外的步骤来启用 S3 和其他 AWS 库所需的客户端 SSL。
The native executable requires some additional steps to enable client SSL that S3 and other AWS libraries need.
-
A custom
bootstrap
script -
libsunec.so
must be added tofunction.zip
-
cacerts
must be added tofunction.zip
要执行此操作,首先使用您的构建创建目录 src/main/zip.native/
。接下来,在 src/main/zip.native/
中创建名为 bootstrap
的 shell 脚本文件,如下所示。在您的构建文件夹(target 或 build)中会自动创建一个示例,名为 bootstrap-example.sh
To do this, first create a directory src/main/zip.native/
with your build. Next create a shell script file called bootstrap
within src/main/zip.native/
, like below. An example is created automatically in your build folder (target or build), called bootstrap-example.sh
#!/usr/bin/env bash
./runner -Djava.library.path=./ -Djavax.net.ssl.trustStore=./cacerts
如果你的 cacerts
文件受密码保护,请在 -Djavax.net.ssl.trustStorePassword=changeit
中添加一个附加集。
Additional set -Djavax.net.ssl.trustStorePassword=changeit
if your cacerts
file is password protected.
接下来,你必须将 GraalVM 发行版中的一些文件复制到 src/main/zip.native/
中。
Next you must copy some files from your GraalVM distribution into src/main/zip.native/
.
GraalVM 版本可能针对这些文件有不同的路径,具体取决于你使用的是 Java 8 还是 Java 11 版本。请相应地进行调整。 |
GraalVM versions can have different paths for these files whether you are using the Java 8 or 11 version. Adjust accordingly. |
cp $GRAALVM_HOME/lib/libsunec.so $PROJECT_DIR/src/main/zip.native/
cp $GRAALVM_HOME/lib/security/cacerts $PROJECT_DIR/src/main/zip.native/
现在,当你运行本地构建时,所有这些文件都会包含在 function.zip
中。
Now when you run the native build all these files will be included within function.zip
如果你使用 Docker 镜像进行构建,则必须从该镜像中提取这些文件。 |
If you are using a Docker image to build, then you must extract these files from this image. |
若要提取所需的 SSL,你必须在后台启动一个 Docker 容器,并附加到该容器以复制制品。
To extract the required ssl, you must start up a Docker container in the background, and attach to that container to copy the artifacts.
首先,让我们启动 GraalVM 容器,并记下容器 ID 输出。
First, let’s start the GraalVM container, noting the container id output.
docker run -it -d --entrypoint bash quay.io/quarkus/ubi-quarkus-mandrel-builder-image:{mandrel-flavor}
# This will output a container id, like 6304eea6179522aff69acb38eca90bedfd4b970a5475aa37ccda3585bc2abdde
# Note this value as we will need it for the commands below
首先,是 libsunec.so
,用于 SSL 实现的 C 库:
First, libsunec.so
, the C library used for the SSL implementation:
docker cp {container-id-from-above}:/opt/graalvm/lib/libsunec.so src/main/zip.native/
其次,cacerts
,证书存储。你可能还需要定期获取更新的副本。
Second, cacerts
, the certificate store. You may need to periodically obtain an updated copy, also.
docker cp {container-id-from-above}:/opt/graalvm/lib/security/cacerts src/main/zip.native/
最终的存档将如下所示:
Your final archive will look like this:
jar tvf target/function.zip
bootstrap
runner
cacerts
libsunec.so
Deploy to AWS Lambda using a Container Image
AWS Lambda 支持通过引用 container images 而不是上传 ZIP 文件来创建 Lambda 函数。这样做会有一些好处,例如绕过上传的 ZIP 文件的大小限制。你可以为本地构建和常规的 JVM 构建定义 Lambda 函数。
AWS Lambda supports creating your lambdas by referencing container images rather than uploading ZIP files. This can have some benefits such as bypassing the size limit of the uploaded ZIP files. You can define lambda functions for both native builds and regular JVM builds.
JVM container image
对于常规的 JVM 发行版,你需要基于官方 AWS Java 基础镜像来构建你的镜像。下面展示了一个 Dockerfile 的示例,该示例将根据你的 Quarkus Lambda 项目创建一个容器镜像。它假定 mvn package
已经执行,并且二进制文件位于 target/
目录中:
For a regular JVM distribution you need to base your image off the official AWS Java base images. Below is an example of a Dockerfile that would create a container image from your Quarkus Lambda project. It assumes that mvn package
has been executed and binaries are available in the target/
directory:
FROM public.ecr.aws/lambda/java:11
ADD target/my-service-0.0.1-SNAPSHOT-runner.jar /var/task/lib/my-service.jar
ADD target/lib/ /var/task/lib/
CMD ["io.quarkus.amazon.lambda.runtime.QuarkusStreamHandler::handleRequest"]
Native executable container image
若要创建一个使用本地可执行文件的 Lambda 容器镜像,我们需要稍作不同。在这种情况下,我们将不需要使用 AWS 的 java:11
基础镜像,而是会使用一个特殊的镜像,假定 Lambda 的运行时环境已提供。下面的示例创建了这样一个容器。它假定已经执行了 Maven 构建(例如 mvn package -Dnative=true
),并且已经将本地二进制文件生成了 target/
目录。二进制文件需要命名为 bootstrap
,并放置在 /var/runtime/
中:
To create a lambda container image that uses the native executable we’ll need to do things a little differently. In this case, we won’t need to use the java:11
base image from AWS, but instead we’ll use a special image that assumes that the runtime environment for the lambda is provided. The example below creates such a container. It assumes that a Maven build has been executed (such as mvn package -Dnative=true
) and has generated the native binary into the target/
directory. The binary needs to be named bootstrap
and be placed in /var/runtime/
:
FROM public.ecr.aws/lambda/provided
ADD target/my-service-0.0.1-SNAPSHOT-runner /var/runtime/bootstrap
RUN chmod ugo+x /var/runtime/bootstrap
CMD ["io.quarkus.amazon.lambda.runtime.QuarkusStreamHandler::handleRequest"]
Deploying a container image lambda
下面,你可以看到如何使用 docker
和 aws
命令行工具构建上面创建的容器镜像并将其部署到 AWS。这些说明适用于本地和 jvm 容器镜像,并且假定 aws
命令行工具已登录。
Below, you can see how the container images created above can be built and deployed to AWS using the docker
and aws
command line tools. These instructions work for both native and jvm container images and assume that the aws
command line tool has been logged in.
Build the Docker image
# Assuming we are located in the root directory of the project and created a Dockerfile there
docker build .
[output omitted]
=> exporting to image 0.0s
=> => exporting layers 0.0s
=> => writing image sha256:[SOME SHA] 0.0s
Create an ECR repository in the users AWS account
aws ecr create-repository --repository-name my/test/quarkus-lambda
Tag the image using your ECR registry information
docker tag [SOME SHA] [YOUR AWS ACCOUNT ID].dkr.ecr.[YOUR AWS ACCOUNT REGION].amazonaws.com/my/test/quarkus-lambda:v1
Log Docker into your ECR registry and push the Docker image to it
aws ecr get-login-password --region region | docker login --username AWS --password-stdin [YOUR AWS ACCOUNT ID].dkr.ecr.[YOUR AWS ACCOUNT REGION].amazonaws.com
docker push [YOUR AWS ACCOUNT ID].dkr.ecr.[YOUR AWS ACCOUNT REGION].amazonaws.com/my/test/quarkus-lambda:v1
Create the AWS lambda function with the AWS CLI tool
确保引用你先前上传的镜像(假定存在一个可用于运行 Lambda 的角色)。请注意,对于 JVM Lambda 函数,默认内存限制 128Mb
不足以运行函数的情况并不少见。在这种情况下,可以通过向 aws lambda create-function
命令提供 --memory-size 256
参数在创建函数时增加内存限制。你还可以在你创建 AWS 控制台中的函数后进行调整。
Make sure you reference the image you uploaded previously (assumes that a role exists that can be used to run the lambda). Please note that it is not unlikely that for the JVM lambda function, the default memory limit of 128Mb
will not be enough to run the function. In that case, you can increase the memory limit when creating the function by providing the --memory-size 256
parameter to your aws lambda create-function
command. You can also adjust the function in the AWS console after you’ve created it.
aws lambda create-function --function-name my-test-quarkus-lambda-function --package-type Image --code ImageUri=[YOUR AWS ACCOUNT ID].dkr.ecr.[YOUR AWS ACCOUNT REGION].amazonaws.com/my/test/quarkus-lambda:v1 --role arn:aws:iam::[YOUR AWS ACCOUNT ID]:role/[SOME ROLE]
现在,你可以使用 AWS 控制台来查看和测试你的新 Lambda 函数。
Now you can use the AWS console to view and test your new lambda function.
Amazon Alexa Integration
若要将 Alexa 与 Quarkus 本地一起使用,你需要使用 Quarkus Amazon Alexa extension hosted at the Quarkiverse Hub。
To use Alexa with Quarkus native, you need to use the Quarkus Amazon Alexa extension hosted at the Quarkiverse Hub.
<dependency>
<groupId>io.quarkiverse.alexa</groupId>
<artifactId>quarkus-amazon-alexa</artifactId>
<version>${quarkus-amazon-alexa.version}</version> 1
</dependency>
1 | Define the latest version of the extension in your POM file. |
通过子类化抽象的 com.amazon.ask.SkillStreamHandler
,按常规方式创建 Alexa 处理程序,并添加请求处理程序实现。
Create your Alexa handler, as normal, by sub-classing the abstract com.amazon.ask.SkillStreamHandler
, and add your request handler implementation.
其它的皆已设定完成了!
That’s all there is to it!
SnapStart
要针对 Lambda SnapStart 优化您的应用程序,请查看 the SnapStart Configuration Documentation。
To optimize your application for Lambda SnapStart, check the SnapStart Configuration Documentation.