Skip to main content

Cloud

Spring Cloud Function with AWS Lambda

A man and woman collaborating and discussing work on a computer

Learning outcome from this article:

  • What is Spring cloud function?
  • What is AWS Lambda?
  • Using Spring Cloud function with AWS Lambda.

Spring Cloud Function

Spring cloud function is one of the Project from Spring cloud Framework. It allows us to create functional applications while retaining all the benefits provided by Spring Boot. It Promote the implementation of business logic via functions. These functions can be stand-alone classes and one can easily deploy on any cloud platform to build a server less framework. Spring Cloud offers a library spring-cloud-starter-function-web allows to build functions with Spring features and it brings all the necessary dependencies.

Why to use Spring Cloud Function?

Spring Cloud Function library allows to the creation of functional applications that can be deployed easily on AWS Lambda or any other serverless cloud platform.

It abstracts away all the transport details and infrastructure, allowing the developer to keep all the familiar tools and processes, and focus firmly on business logic.

Features of Spring Cloud Function

  • REST support to expose functions as HTTP endpoints etc.
  • Deploying functions packaged as JAR files with an isolated class loader, to support multi-version deployments in a single JVM.
  • Choice of programming styles – reactive, imperative or hybrid.
  • POJO functions (i.e., if something fits the @FunctionalInterface semantics we’ll treat it as function)
  • Transparent type conversion of inputs and outputs.
  • Function composition which includes composing imperative functions with reactive.

Example Application

Below example is created with Spring Cloud Function which allow the standard Java 8 functional support with Supplier, Function, and Consumer support and GET/POST request can be created with this.

GET Supplier<Output>
POST Consumer<Input>
GET/POST Function<Input, Output>

In below code methods can be called as REST end points with the help of method name.

@SpringBootApplication
public class SpringCloudFunctionExampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringCloudFunctionExampleApplication.class, args);
    }

    @Bean
    public Function<String, String> function() {
          return input -> input;
    }

    @Bean
    public Consumer<String> consume() {
        return input -> System.out.println("Input: " + input);
    }

    @Bean
    public Supplier<String> supply() {
        return () -> "Hello";
    }

}

Exposed Functions as Endpoints (Multiple function single class)

Consumer – /consume – expects an input

curl -H ‘Content-Type:text/plain’ http://localhost:8080/consume -d ‘Welcome’

Function – /function – expects an input and output

curl -H ‘Content-Type:text/plain’ http://localhost:8080/function -d ‘Welcome’

Welcome ⏎

Supplier – /supply – returns an output

curl -H ‘Content-Type:text/plain’ http://localhost:8080/supply

Hello ⏎

Other Way of Implementing Function:

If we don’t want to expose multiple functions in a single class and want to maintain separate class for separate Function, then we can go with below approach. For this approach spring.cloud.function.scan.packages property must be updated in application.properties file to scan below class for function as Rest end point.

public class Welcome implements Function<String, String>{
@Override
    public String apply(String s) {
        return "Hello " + s;
    }
}

Exposed Function as Endpoints(Single function single class)

Function – /welcome – expects an input and output

curl -H ‘Content-Type:text/plain’ http://localhost:8080/welcome -d ‘ and Welcome’

Hello and Welcome⏎

In similar way we can create other implementations for by extending Supplier and Consumer class and by implementing their respective methods.

AWS Lambda

AWS Lambda is a serverless, event-driven compute service that lets you run code for virtually any type of application or backend service without provisioning or managing servers. You can trigger Lambda from over 200 AWS services and software as a service (SaaS) application, and only pay for what you use.

Why to use AWS Lambda?

  • With AWS Lambda, you can run code without provisioning or managing servers.
  • You pay only for the compute time that you consume—there’s no charge when your code isn’t running.
  • You can run code for virtually any type of application or backend service—all with zero administration.
  • In Free tier subscription user can get 1million free request per month for AWS lambda.

Features of AWS Lambda

Below are the key Features of AWS Lambda:

  • Auto Scaling
  • Concurrency control
  • Function URLs
  • Event source mappings

Pricing in AWS Lambda

AWS Lambda is a pay per use service, meaning you only pay what you use, therefore you are charged on the following parameters

  • The number of requests that you make to your lambda function
  • The duration for which your code executes

Spring Cloud Function with AWS Lambda

We can create jar by maven build with the example considered in Spring Cloud Function section. AWS Lambda supports only function. Below are the required dependencies to deploy spring cloud function on AWS lambda.

       <dependency>

            <groupId>org.springframework.cloud</groupId>

            <artifactId>spring-cloud-function-adapter-aws</artifactId>

        </dependency>

        <dependency>

            <groupId>com.amazonaws</groupId>

            <artifactId>aws-lambda-java-events</artifactId>

            <version>2.0.2</version>

        </dependency>

        <dependency>

            <groupId>com.amazonaws</groupId>

            <artifactId>aws-lambda-java-core</artifactId>

            <version>1.1.0</version>

        </dependency>

Multiple Spring Cloud Function in single Project

In an AWS Lambda only one function can be used at a time. Instead of having multiple projects defining their own function we can create a single application with multiple different functions defined within it. This project can be deployed multiple times across different Lambda and configuring respective FUNCTION_NAME in Lambda.

The AWS adapter takes a Spring Cloud Function app and converts it to a form that can run in AWS Lambda.

If we are using spring boot application, Lambda always search for request handler class which can be created simply by extending SpringBootRequestHandler class by specifying input and output to the function. In this example we are used String as input and output type. So, we have included below InputHandler class for this example.

public class InputHandler extends SpringBootRequestHandler<String,String> {

}

 Build and Deploy Spring Cloud Function to AWS Lambda

  • Below command can be used to build application into a JAR file that you can deploy into AWS for your Lambda.

         mvn clean package

Steps to Deploy and Test Jar file in AWS Lambda

  1. Login to AWS Console and navigate to the AWS Lambda service.
  2. From AWS Lambda Dashboaerd, click on Create Function. It will redirect to below page. Select Author from scratch, Enter Function Name, select Language as Java8 or Java 11 in Runtime info and click on create Function.

Picture1

  1. Select Upload from .zip or .jar file to upload and save the application jar created.                                        Picture2
  2. Go to runtime setting, click on edit and update Handler info which we created in our application. In this example we have created InputHandler class. Update fully qualified class name (package+class name) in Handler info.                                                                                                                                                  Picture3
  3. Click on Configuration tab -> select Environment Variable -> Add Environment variable. Update function that needs to be mapped to Lambda as shown below. Here we have mapped supply as FUNCTION_NAME. Based on our requirement we can update this Environment variable to map desired function to Lambda.                                                                                                                                        Picture4
  4. Go to Test tab -> create new event -> update the Event name-> provide required input in Event JSON -> click on Save -> click on Test. Here we have provided supply as function name where no input is needed, we can update Event JSON as empty string, save and Test this Spring cloud Function as Lambda.                                                                                                                                                          Picture5
  1. In below image we can see output is displayed, provided with other details like summary, Log output etc. Also Lambda provides link for log in this page which will redirect to CloudWatch to check complete log for this Lambda.

Picture6

  1. Lambda also provides Monitor, Aliases, and Versions tabs to monitor runtime metrics and to maintain aliases and version details. A dedicated endpoint can also be created for public or private use in Configuration->Function URL.

And yes, this is it!!

We have learned about Spring cloud function, AWS Lambda, Deployment of Spring cloud function in AWS Lambda and different use cases.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Chandan P Singh

Chandan is a Lead Technical Consultant at Perficient Nagpur. He is enthusiastic and highly skilled in developing Java, Spring boot, Spring cloud, and microservices software.

More from this Author

Follow Us