Dual Spring Boot and AWS Lambda Project



Sometimes, we need to convert an existing Spring Boot application to AWS Lambda function, often due to upgrade in technology or company's new direction to the sky.. I mean cloud and beyond...

In some extremely rare case we might be forced to write a dual Spring Boot and AWS Lambda project, that is a project that can run as a Spring Boot application in its embedded Tomcat container and also can be uploaded as AWS Lambda function. This usually happens when one of the developer in the team has had one too many "discussions" about Spring Boot or Lambda that he proceeded to create dual app while the rest of the team going round and round in circle.

Luckily, awslabs has answer to that, they call it Serverless Java Containerhttps://github.com/awslabs/aws-serverless-java-container


Here is my simple example on how to achieve the dual Spring Boot x AWS Lambda application:

The source: https://github.com/overtakerx/springbootawslambdademo contains a simple typical Spring Boot application with four additional items:


aws-serverless-java-container-spring library as dependency in build.gradle


a task to build a zip file besides the original spring boot jar



new StreamLambdaHandler class


Spring Boot main application has to extend SpringBootServletInitializer



You could try ./gradlew bootRun and you can see that the Spring Boot application still functions as it should be, because it simply ignore the Handler class.

The AWS Lambda part is slightly trickier, go to AWS Lambda console and upload the zip file that has been assembled (note do not upload the spring boot jar file, it would not work)

Next, do not bother to get the test to work in AWS Lambda console, it requires you to recreate the massive aws proxy request json, which in my opinion, is too much of a work. Instead, go to API Gateway console...



And create a new API endpoint or reuse any of your existing one, and create a new child resource and configure it as proxy resource (this is important, if you don't do this one, you will be scratching your head for hours), leave everything as is and click create.




Finally, on the API Gateway test page, we specify the Method, the Path, Request Body if needed and Header (note this is important too as our Spring Boot application is expecting json, it needs to have the right content type header or else it will just return internal server error).

That's it!, of course this is grossly over simplified demo of the dual app, however it is a good beginner start, and a proof that it is do-able, happy dualing!


Further Reading:




Comments

Popular posts from this blog

Spring Boot 2: Parallelism with Spring WebFlux

Spring Boot Reactive API Part 2