Introduction To Spring Cloud Function

Amaresh Pattanayak
2 min readJul 20, 2019

--

Spring Cloud Function is a powerful tool for decoupling the business logic from any specific runtime target. We are going to use Spring boot + java 8 features to create our serverless cloud function.

Step1:-Create a spring boot starter project and add following spring cloud function dependency.

<dependency>

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

<artifactId>spring-cloud-starter-function-web</artifactId>

<version>1.0.1.RELEASE</version>

</dependency>

Step2:- Now let’s expose the java-8 functional interfaces using @Beans annotation.

package SpringBootCloudFunction.SpringBootCloudFunction;

import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class SpringBootCloudFunctionApplication {

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

@Bean public Consumer<String> consumerTest() {
return value -> System.out.println(“consumerTest {} you have entered — ->” + value);
}

@Bean public Function<String, String> functionTest() {
return value -> new String(“supplier test using spring cloud function {} and you have entered “+value);
}

@Bean Supplier<String> supplierTest() {
return () -> new String(“supplierTest {} supplier test using spring cloud function”);
}

}

Spep3:-Now we are done, Lets test our functions. The beauty of this serverless architecture is, we don’t need to care about the request mapping and all. We can use simply the function name as request uri.

As supplier does not take any argument. We can access it by HTTP GET. Use your favorite rest client, I am using postman here.

And for the function and consumer, we have to use HTTP POST with content type as text.

Note:- If you are implementing the functional interfaces in another package, then you need to specify in application.properties file and you don’t need to use @bean annotation. For example:-

public class myService implements Function<String, String> {

@Override

public String apply(String s) {

return “Hello “ + s + “, we are testing Spring Cloud Function!!!”;

}

And the package name should be added as spring.cloud.function.scan.packages=com.spring.cloudfunction.functions.example.service

Find this code @ https://github.com/amaresh8053/Spring-Boot-Cloud-Function.git

Hope you like this tutorial. Have a good day :)

--

--

No responses yet