Open In App

Serverless Functions with Spring Cloud Function

Serverless computing in Spring Boot is popular because of its simplicity and low cost. Working serverless allows us to focus on writing code without worrying about managing infrastructure. Spring Cloud Function is a framework that can enable serverless services using the Spring ecosystem. It allows developers to write projects as spring beans and use them.

Spring Cloud Function can provide a simple and consistent programming model for creating serverless functions. It can allow the developers to write the functions as Spring beans which can be developed as serverless applications. Creating the functions as the beans and exposing them as the HTTP endpoints or integrating them with the messaging systems.

Implementation of Serverless Functions with Spring Cloud Function

Using Java Spring Boot and WebSocket, we can easily create a simple application.

Step 1: Create a spring project, using spring initializr, and add the below dependencies in the project.

Dependencies:

After successfully creating the project, the file structure will look like the below image.

Project Structure

Step 2: Create the new package and it named as function in that package create the new Java class and it named as the UppercaseFunction.

Go to src > java > main > com.example.serverlessfunctiondemo > function > UppercaseFunction and put the below code.

/**
 * A Spring Cloud Function implementation that converts a given string to uppercase.
 */
@Component
public class UppercaseFunction implements Function<String, String> {

    /**
     * Input string converted to uppercase.
     */
    @Override
    public String apply(String input) {
        return input.toUpperCase();
    }
}


Step 3: Create the new package and it named as controller in that package create the new Java class and it named as the FunctionController.

Go to src > java > main > com.example.serverlessfunctiondemo > controller > FunctionController and put the below code.

/**
 * Controller class responsible for handling HTTP requests related to the uppercase conversion function.
 */
@RestController
public class FunctionController {

    /**
     * Endpoint to convert a given string to uppercase.
     */
    @PostMapping("/api/uppercase")
    public String convertToUppercase(@RequestBody String input) {
        return input.toUpperCase();
    }
}


Step 4: Create the new Java class and it named as the FunctionControllerTest.

Go to src > java > main > com.example.serverlessfunctiondemo > Test > FunctionControllerTest and put the below code.

package com.example.serverlessfunctionsdemo;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

/**
 * This class provides unit tests for the FunctionController class. It ensures that the functionality 
 * of converting a string to uppercase works as expected.
 */
@SpringBootTest
@AutoConfigureMockMvc
public class FunctionControllerTest {

    @Autowired
    private MockMvc mockMvc;

    /**
     * Test case to verify the behavior of converting a string to uppercase in the FunctionController class.
     * @throws Exception if any error occurs during the test execution
     */
    @Test
    public void testConvertToUppercase() throws Exception {
        String input = "hello world";
        String expectedOutput = "HELLO WORLD";

        mockMvc.perform(MockMvcRequestBuilders.post("/api/uppercase")
                        .contentType(MediaType.TEXT_PLAIN)
                        .content(input))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().string(expectedOutput));
    }
}


Step 5: Now, open the main class file and write the below code.

/**
 * Main class responsible for starting the serverless functions demo application.
 */
@SpringBootApplication
public class ServerlessFunctionsDemoApplication {

    /**
     * Main method to start the application.
     */
    public static void main(String[] args) {
        SpringApplication.run(ServerlessFunctionsDemoApplication.class, args);
    }

}


Step 6: Once we completed all the steps, run the project as the Spring boot application and it will start at port 8080. Refer the below console output image for the better understanding.

Application started


Step 7: Test the Application

Testing Successful

Output:

Uppercase API:

POST http://localhost:8080/api/uppercase

Refer the below image:

Output in Postman

If we follow the above steps, then we can successfully demonstrate the serverless functions with Spring Cloud function of the spring project.

Article Tags :