1

How will the Lambda handler of multiple different types of trigger look like in java? I want to set a trigger for Cloudwatch Event Rule, S3. How can I do this?

public class App implements RequestHandler<S3Event, Context>
{
public Context handleRequest(S3Event s3event, Context context) {
     System.out.println("welcome to lambda");
    }
}
nats
  • 187
  • 2
  • 13
  • Do you mean a single lambda will be triggered by multiple different types of trigger (S3Event and ScheduledEvent, for example) ? – matt freake Mar 19 '21 at 09:21
  • @mattfreake Yes – nats Mar 19 '21 at 10:14
  • Why do you want to do this? – Parsifal Mar 19 '21 at 12:54
  • The stream solution below definitely works, but lambdas are meant to be small units of code, so it can be a red flag that your lambda is trying to do too much. You are also limiting your ability to manage the processing of the types of event differently, if you only have one lambda whose concurrency etc you can modify – matt freake Mar 20 '21 at 08:27

2 Answers2

2

You can use Map<String,String> as input

public class Handler implements RequestHandler<Map<String,String>, String>{
  @Override
  public String handleRequest(Map<String,String> event, Context context) {
  }
}

Or use RequestStreamHandler and parse the InputStream to the correct object.

public class HandlerStream implements RequestStreamHandler {
  @Override
  public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {
  }
}
k1r0
  • 542
  • 1
  • 5
  • 12
0

using a generic Object could work, I use Serverless Framework with:

package com.serverless;

import java.util.Collections;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

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

public class Handler implements RequestHandler<Object, Object> {

    private static final Logger LOG = LogManager.getLogger(Handler.class);

    @Override
    public Object handleRequest(final Object input, final Context context) {
        LOG.info("received: {}", input);
        return input;
    }
}
oieduardorabelo
  • 2,687
  • 18
  • 21