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

最后修改: 2017年 1月 5日


1. Introduction


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.


2. Maven Dependencies


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

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


This dependency can be found at Maven repository.


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

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


3. Create Handler


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


  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


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.


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


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

3.2. RequestHandler Interface


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


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


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


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


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


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.


5. Create Lambda Function via Management Console


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:


  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


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


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.