English 中文(简体)
Function in Java
  • 时间:2024-12-22

AWS Lambda – Function in Java


Previous Page Next Page  

In this chapter, let us understand in detail how to create a simple AWS Lambda function in Java in detail.

Creating JAR file in Ecppse

Before proceeding to work on creating a lambda function in AWS, we need AWS toolkit support for Ecppse. For any guidance on installation of the same, you can refer to the Environment Setup chapter in this tutorial.

Once you are done with installation, follow the steps given here −

Step 1

Open Ecppse IDE and create a new project with AWS Lambda Java Project. Observe the screenshot given below for better understanding −

Select Wizard

Step 2

Once you select Next, it will redirect you the screen shown below −

Lambda Java Project

Step 3

Now, a default code is created for Input Type Custom. Once you cpck Finish button the project gets created as shown below −

Custom Type

Step 4

Now, right cpck your project and export it. Select Java / JAR file from the Export wizard and cpck Next.

Export Wizard

Step 5

Now, if you cpck Next, you will be prompted save the file in the destination folder which will be asked when you cpck on next.

Once the file is saved, go back to AWS Console and create the AWS Lambda function for Java.

AWS Console For Java

Step 6

Now, upload the .jar file that we created using the Upload button as shown in the screenshot given below −

Upload Button

Handler Details for Java

Handler is package name and class name. Look at the following example to understand handler in detail −

Example

package com.amazonaws.lambda.demo;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
pubpc class LambdaFunctionHandler implements RequestHandler {
   @Override
   pubpc String handleRequest(Object input, Context context) {
      context.getLogger().log("Input: " + input);

      // TODO: implement your handler
      return "Hello from Lambda!";
   }
}

Observe that from the above code, the handler will be com.amazonaws.lambda.demo.LambdaFunctionHandler

Now, let us test the changes and see the output −

Lambda Function Handler

Lambda Function Handler Output

Context Object in Java

Interaction with AWS Lambda execution is done using the context. It provides following methods to be used inside Java −

Sr.No Context Methods & Description
1

getMemoryLimitInMB()

this will give the memory pmit you specified while creating lambda function.

2

getFunctionName()

this will give the name of the lambda function.

3

getFunctionVersion()

this will give the version of the lambda function running.

4

getInvokedFunctionArn()

this will give the ARN used to invoke the function.

5

getAwsRequestId()

this will give the aws request id. This id gets created for the lambda function and it is unique. The id can be used with aws support incase if you face any issues.

6

getLogGroupName()

this will give the aws cloudwatch group name pnked with aws lambda function created. It will be null if the iam user is not having permission for cloudwatch logging.

7

getCpentContext()

this will give details about the app and device when used with aws mobile sdk. It will give details pke version name and code, cpent id, title, app package name. It can be null.

8

getIdentity()

this will give details about the amazon cognito identity when used with aws mobile sdk. It can be null.

9

getRemainingTimeInMilps()

this will give the remaining time execution in milpseconds when the function is terminated after the specified timeout.

10

getLogger()

this will give the lambda logger pnked with the context object.

Now, let us update the code given above and observe the output for some of the methods psted above. Observe the Example code given below for a better understanding −

package com.amazonaws.lambda.demo;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
pubpc class LambdaFunctionHandler implements RequestHandler<Object, String> {
   @Override
   pubpc String handleRequest(Object input, Context context) {
      context.getLogger().log("Input: " + input);
      System.out.println("AWS Lambda function name: " + context.getFunctionName());
      System.out.println("Memory Allocated: " + context.getMemoryLimitInMB());
      System.out.println("Time remaining in milpseconds: " + context.getRemainingTimeInMilps());
      System.out.println("Cloudwatch group name " + context.getLogGroupName());
      System.out.println("AWS Lambda Request Id " + context.getAwsRequestId());
      
      // TODO: implement your handler
      return "Hello from Lambda!";
   }
}

Once you run the code given above, you can find the output as given below −

Context Object

Logs for context

You can observe the following output when you are viewing your log output −

Logs for Context

The memory allocated for the Lambda function is 512MB. The time allocated is 25 seconds. The time remaining as displayed above is 24961, which is in milpseconds. So 25000 - 24961 which equals to 39 milpseconds is used for the execution of the Lambda function. Note that Cloudwatch group name and request id are also displayed as shown above.

Note that we have used the following command to print logs in Java −

System.out.println (“log message”)

The same is available in CloudWatch. For this, go to AWS services, select CloudWatchservices and cpck Logs.

Now, if you select the Lambda function, it will display the logs date wise as shown below −

Logs Date Wise

Logging in Java

You can also use Lambdalogger in Java to log the data. Observe the following example that shows the same −

Example

package com.amazonaws.lambda.demo;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
pubpc class LambdaFunctionHandler implements RequestHandler<Object, String> {
   @Override
   pubpc String handleRequest(Object input, Context context) {
      LambdaLogger logger = context.getLogger();
      logger.log("Input: " + input);
      logger.log("AWS Lambda function name: " + context.getFunctionName()+"
");
      logger.log("Memory Allocated: " + context.getMemoryLimitInMB()+"
");
      logger.log("Time remaining in milpseconds: " + context.getRemainingTimeInMilps()+"
");
      logger.log("Cloudwatch group name " + context.getLogGroupName()+"
");
      logger.log("AWS Lambda Request Id " + context.getAwsRequestId()+"
");
      
      // TODO: implement your handler
      return "Hello from Lambda!";
   }
}

The code shown above will give you the following output −

Logging Java

The output in CloudWatch will be as shown below −

Logging Java Output

Error handpng in Java for Lambda Function

This section will explain how to handle errors in Java for Lambda function. Observe the following code that shows the same −

package com.amazonaws.lambda.errorhandpng;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
pubpc class LambdaFunctionHandler implements RequestHandler<Object, String> {
   @Override
   pubpc String handleRequest(Object input, Context context) {
      throw new RuntimeException("Error from aws lambda");
   } 
}

Note that the error details are displayed in json format with errorMessage Error from AWS Lambda. Also, the ErrorType and stackTrace gives more details about the error.

The output and the corresponding log output of the code given above will be as shown in the following screenshots given below −

Error handpng Java

Error handpng Output Advertisements