Trigger AWS Lambda Programmatically in Java
Posted By Mohd Adnan | 26-Sep-2018
Image Credits: AWS
AWS Lambda has already been adopted by most of the companies and it has proved itself. A serverless architecture is in huge trend nowadays.
Working on AWS Lambda - there are requirements where you have to take control of AWS Lambda invocation when needed rather than running at fixed intervals through AWS CloudWatch Events or AWS Gateway API.
AWS is continuously working on developers pain points and has provided a great set of APIs, thus invoking AWS Lambda through code is possible. Here, I will be providing steps on invoking AWS Lambda through Java code.
In scenarios - where we have a tasks added in Queue and it needs to be processed using a Consumer/Worker Lambda pattern. Figure below shows all the components (Queue, CloudWatch Event, Consumer Lambda, Worker Lambdas)
Image Credits: CloudCraft
1. The Queue stores tasks from other parts of the system
2. A Consumer Lambda triggered by CloudWatch event on a schedule
3. The Consumer Lambda reads messages in its execution time and executes a Worker Lambda for each message
4. The Worker Lambda performs the actual tasks and acknowledges message from the queue
Worker Lambda invocation can be achieved in following steps:
Add Dependency to build.gradle
Classes required to import
import com.amazonaws.regions.Regions; import com.amazonaws.services.lambda.AWSLambda; import com.amazonaws.services.lambda.AWSLambdaClientBuilder; import com.amazonaws.services.lambda.model.InvokeRequest; import com.amazonaws.services.lambda.model.InvokeResult;
1. Instantiate AWS Client Builder with Credentials and Region where your Lambda function has to be invoked
AWSLambdaClientBuilder builder = AWSLambdaClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(awsCreds)).withRegion(Regions.EU_WEST_1); AWSLambda client = builder.build();
2. Create an InvokeRequest object with required parameters
InvokeRequest synchronousRequest = new InvokeRequest().withFunctionName(function) .withPayload(jsonPayload);
Note: The above request will invoke Lambda syncrhonously, however if you want to invoke Lambda asynchronously - you can add a InvocationType parameter as Event as below:
InvokeRequest asyncRequest = new InvokeRequest().withFunctionName(function) .withInvocationType(InvocationType.Event) .withPayload(jsonPayload);
3. Invoke the request
InvokeResult invokeResult = client.invoke(synchronousRequest);
4. Get the status code to identify success
if (invokeResult.getStatusCode() >= 200 && invokeResult.getStatusCode() < 300) return "SUCCESS";
Hope that helps, please comment in case of any queries.