How to create a Lambda function, Java 8, AWS Lambda, SAM CLI and testing/debuging locally.
In this tutorial, we will see how easy to develop a Lambda function using AWS Serverless services, AWS Lambda and SAM (AWS Serverless Application Model) CLI. To get a running environment, I will use Docker for Windows, Java 8, Spring Tool Suite (STS) and Power Shell on a Windows 10 machine. You will also need an AWS account.
You can also download the complete code from GitHub.
- Create an AWS user with programmatic access (tutorial user is aws-sam-developer-user). Save the credentials locally.
I will use SAM CLI to create a sample Lambda function and change the code for our tutorial.
2. Open Power Shell. Verify that SAM is installed successfuly.
3. Run aws configure command using the AWS user with programmatic access.
4.1 Using Power Shell, cd into the folder where you want to save your STS workspace. In this folder we will create the sample project for the new Lambda function.
4.2 Run init SAM command using the following selections. The name of the project is “customer-microservice-rest-api”.
Now you should see a sample project under “customer-microservice-rest-api” folder. In this folder you have your sample application which is named as HelloWorldFunction (also events folder and template.yml file).
5.1 Using STS, import the Maven project.
5.2 Change the handleRequest function as follows.
Now lambda function is ready. Let’s change the related configurations in template.yml file.
6. Move the template.yml into the project folder (same as pom.xml). Open and update the template.yml file.
7. Open Power Shell. Go to folder where template.yml file is stored. Run sam build command.
Now lambda function is ready to test.
While testing the Lambda function locally, a new docker container will run in the background. Hence, you should have your Docker for Windows up and running.
8.1 In the same folder, run sam local invoke CreateCustomerHandlerLambdaFunction — event …\customer-microservice-rest-api\events\event.json command. In the first go, it may take up to 5 minutes.
You should get the successful response in the Power Shell.
8.2 If you want to debug the lambda function. You need to configure a debug for Remote Java Appliction.
8.3 Put a breakpoint the lambda fuction.
8.4 Run “sam local invoke” command with –d 5959 parameter. “sam local invoke CreateCustomerHandlerLambdaFunction — event …\customer-microservice-rest-api\events\event.json -d 5959”