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.
Update src/main/java/com/serverless/Handler.java as below:
src/main/java/com/serverless/Handler.java
Copy
Ask AI
package com.serverless;import java.util.Map;import com.amazonaws.services.lambda.runtime.Context;import com.amazonaws.services.lambda.runtime.RequestHandler;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("lasting-roughy-29092.upstash.io", 6379, true); jedis.auth("********"); Long value = jedis.incr("counter"); jedis.close(); 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 Redis Console -> Your Database -> Connect to your database -> Java.