A Basic AWS Lambda Example With Java – 使用Java的基本AWS Lambda实例

最后修改: 2017年 1月 5日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

AWS Lambda is a serverless computing service provided by Amazon to reduce the configuration of servers, OS, Scalability, etc. AWS Lambda is capable of executing code on AWS Cloud.

AWS Lambda是由Amazon提供的无服务器计算服务,以减少服务器、操作系统、可扩展性等方面的配置。AWS Lambda能够在AWS云上执行代码。

It runs in response to events on different AWS resources, which triggers AWS Lambda functions. Pricing is pay-as-you-go which means we won’t shell our money on idle lambda functions.

它响应不同AWS资源上的事件而运行,从而触发AWS Lambda函数。定价是现收现付,这意味着我们不会在闲置的lambda函数上掏钱。

This tutorial requires a valid AWS account; you can create one here.

本教程需要一个有效的AWS帐户;您可以在这里创建一个

2. Maven Dependencies

2.Maven的依赖性

To enable AWS lambda, we need the following dependency in our project:

为了启用AWS lambda,我们的项目中需要有以下依赖关系。

<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-lambda-java-core</artifactId>
    <version>1.1.0</version>
</dependency>

This dependency can be found at Maven repository.

该依赖关系可以在Maven仓库找到。

We also need the Maven Shade Plugin to build the lambda application:

我们还需要Maven Shade Plugin来构建lambda应用程序。

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>2.4.3</version>
    <configuration>
        <createDependencyReducedPom>false</createDependencyReducedPom>
    </configuration>
    <executions>
        <execution>
            <phase>package</phase>
	    <goals>
                <goal>shade</goal>
            </goals>
        </execution>
    </executions>
</plugin>

3. Create Handler

3.创建处理程序

Simply put, to invoke a lambda function, we need to specify a handler; there are 3 ways of creating a handler:

简单地说,要调用一个lambda函数,我们需要指定一个处理程序;有3种创建处理程序的方法。

  1. Creating a custom MethodHandler
  2. Implementing the RequestHandler interface
  3. Implementing the RequestStreamHandler interface

Let’s see how to do it using code examples.

让我们用代码实例来看看如何做到这一点。

3.1. Custom MethodHandler

3.1.自定义方法处理程序

We’ll create a handler method that will be the entry point for incoming requests. We can use JSON format or primitive data types as input values.

我们将创建一个处理方法,作为传入请求的入口。我们可以使用JSON格式或原始数据类型作为输入值。

Also, the optional Context object will allow us to access useful information available within the Lambda execution environment:

此外,可选的Context对象将允许我们访问Lambda执行环境中可用的有用信息。

public class LambdaMethodHandler {
    public String handleRequest(String input, Context context) {
        context.getLogger().log("Input: " + input);
        return "Hello World - " + input;
    }
}

3.2. RequestHandler Interface

3.2.RequestHandler接口

We can also implement the RequestHandler into our class and override the handleRequest method which will be our entry point for requests:

我们还可以在我们的类中实现RequestHandler,并覆盖handleRequest方法,这将是我们的请求入口。

public class LambdaRequestHandler
  implements RequestHandler<String, String> {
    public String handleRequest(String input, Context context) {
        context.getLogger().log("Input: " + input);
        return "Hello World - " + input;
    }
}

In this case, the input will be the same as in the first example.

在这种情况下,输入将与第一个例子中的相同。

3.3. RequestStreamHandler Interface

3.3.RequestStreamHandler接口

We can also implement RequestStreamHandler in our class and simply override the handleRequest method.

我们也可以在我们的类中实现RequestStreamHandler并简单地覆盖handleRequest方法。

The difference is that InputStream, ObjectStream and Context objects are being passed as parameters:

不同的是,InputStreamObjectStreamContext对象被作为参数传递。

public class LambdaRequestStreamHandler
  implements RequestStreamHandler {
    public void handleRequest(InputStream inputStream, 
      OutputStream outputStream, Context context) {
        String input = IOUtils.toString(inputStream, "UTF-8");
        outputStream.write(("Hello World - " + input).getBytes());
    }
}

4. Build Deployment File

4.建立部署文件

With everything configured, we can create the deployment file by simply running:

在配置好一切之后,我们可以通过简单地运行来创建部署文件。

mvn clean package shade:shade

The jar file will be created under the target folder.

jar文件将在target文件夹下创建。

5. Create Lambda Function via Management Console

5.通过管理控制台创建Lambda函数

Sign in to AWS Amazon and then click on Lambda under services. This page will show the lambda functions list, which is already created.

登录AWS Amazon,然后点击服务下的Lambda。这个页面将显示lambda函数列表,它已经被创建。

Here are the steps required to create our lambda:

下面是创建我们的lambda所需的步骤。

  1. “Select blueprint” and then select “Blank Function”
  2. “Configure triggers” (in our case we don’t have any triggers or events)
  3. “Configure function”:
    • Name: Provide MethodHandlerLambda,
    • Description: Anything that describes our lambda function
    • Runtime: Select java8
    • Code Entry Type and Function Package: Select “Upload a .ZIP and Jar file” and click on “Upload” button. Select the file which contains lambda code.
    • Under Lambda function handler and role:
      • Handler name: Provide lambda function handler name com.baeldung.MethodHandlerLambda::handleRequest
      • Role name: If any other AWS resources are used in lambda function, then provide access by creating/using existing role and also define the policy template.
    • Under Advanced settings:
      • Memory: Provide memory that will be used by our lambda function.
      • Timeout: Select a time for execution of lambda function for each request.
  4. Once you are done with all inputs, click “Next” which will show you to review the configuration.
  5. Once a review is completed, click on “Create Function”.

6. Invoke the Function

6.调用函数

Once the AWS lambda function is created, we’ll test it by passing in some data:

一旦AWS lambda函数被创建,我们将通过传入一些数据来测试它。

  • Click on your lambda function from lists and then click on “Test” button
  • A popup window will appear which contains dummy value for sending data. Override the data with “Baeldung”
  • Click on “Save and test” button

On the screen, you can see the Execution result section with successfully returned output as:

在屏幕上,你可以看到执行结果部分,成功返回的输出为。

"Hello World - Baeldung"

7. Conclusion

7.结论

In this quick intro article, we’ve created a simple AWS Lambda app using Java 8, deployed that to AWS and tested it.

在这篇快速介绍文章中,我们使用Java 8创建了一个简单的AWS Lambda应用,将其部署到AWS并进行了测试。

The full source code for the example app can be found over on Github.

示例应用程序的完整源代码可以在Github上找到over