Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS Lambda RequestHandler for a void output

Consider a simple Lambda written in Java:

import com.amazonaws.services.lambda.runtime.Context; 
import com.amazonaws.services.lambda.runtime.RequestHandler;

public class Hello implements RequestHandler<Integer, String>{
    public String handleRequest(int myCount, Context context) {
        return String.valueOf(myCount);
    }
}

The handler interface is defined as RequestHandler<InputType, OutputType>, but when my Lambda reacts to events and just does some side effects, is the output type unnecessary and I have to write something like this:

public class Hello implements RequestHandler<SNSEvent, Void>{
    public Void handleRequest(SNSEvent snsEvent, Context context) {
        ...
        return null;
    }
}

Which is annoying.

Is there an alternative to RequestHandler for a void handler?:

public class Hello implements EventHandler<SNSEvent>{
    public void handleEvent(SNSEvent snsEvent, Context context) {
        ...
    }
}
like image 247
ttulka Avatar asked Mar 19 '19 10:03

ttulka


People also ask

Can Lambda continue after returning response?

No, this isn't possible.

Does Lambda scale automatically?

It "scales" automatically by running in parallel on AWS infrastructure. You only pay while a function is running, per 100ms. It is the job of AWS to ensure that their back-end infrastructure scales to support the number of Lambda functions being run by all customers in aggregate.

What is RequestHandler in Java?

The RequestHandler interface is a generic type that takes two parameters: the input type and the output type. Both types must be objects. When you use this interface, the Java runtime deserializes the event into an object with the input type, and serializes the output into text.


1 Answers

You don't need to implement an interface for your Lambda entry point. Your handler class can just be a POJO with a signature that fulfils the requirements explained in the documentation.

For example:

package example;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.events.SNSEvent;

public class Hello {
  public void handleEvent(SNSEvent event, Context context) {
    // Process the event
  }
}

In this case you should use example.Hello::handleEvent as the handler configuration.

See also this example from the official docs:

package example;

import com.amazonaws.services.lambda.runtime.Context; 
import com.amazonaws.services.lambda.runtime.LambdaLogger;

public class Hello {
    public String myHandler(int myCount, Context context) {
        LambdaLogger logger = context.getLogger();
        logger.log("received : " + myCount);
        return String.valueOf(myCount);
    }
}
like image 144
Ferdinand Beyer Avatar answered Sep 28 '22 09:09

Ferdinand Beyer