Skip to main content

Serverless API with Java and Redis

In this tutorial, we will build a stateful serverless API using Java and Redis on AWS Lambda. The API will simply count the page views and return it as http response.


  • Install node and npm
  • Install the Serverless Framework installed with an AWS account set up.
  • Install JDK and not Java JRE. Set your JAVA_HOME.
  • Install Apache Maven.
  • Create a free Serverless Redis database from Upstash as described here.

Project Setup#

  • Create the project:

serverless create --template aws-java-maven --name serverless-api-java-redis -p serverless-api-java-redis

  • Add jedis as dependency to the pom.xml:

    <dependency>   <groupId>redis.clients</groupId>   <artifactId>jedis</artifactId>   <version>3.6.0</version></dependency>
  • Update serverless.yml adding an http endpoint as below:
functions: hello:   handler: com.serverless.Handler   events:     - httpApi:         path: /hello         method: get

The Code#

Update as below:

package com.serverless;
import java.util.Map;
import;import;import redis.clients.jedis.Jedis;
public class Handler implements RequestHandler<Map<String, Object>, ApiGatewayResponse> {  @Override  public ApiGatewayResponse handleRequest(Map<String, Object> input, Context context) {     Jedis jedis = new Jedis("", 32618, true);     jedis.auth("d5033b46dfbgheb6718f9dbbd2925");     Long value = jedis.incr("counter");     String message = "Hello World, Count:" + value;     return ApiGatewayResponse.builder()           .setStatusCode(200)           .setObjectBody(message)           .build();  }}

In the above code, you need to replace your Redis endpoint and password. You can copy Jedis connection code from the Upstash console.

Deploy and Run#

First build your project with mvn clean install. Then deploy to AWS with serverless deploy. The last command will output the endpoint URL as below:

Serverless: Stack update finished...
Service Information
service: serverless-api-java-redis
stage: dev
region: us-east-1
stack: serverless-api-java-redis-dev
resources: 11
api keys:
  GET -
  hello: serverless-api-java-redis-dev-hello