在JAVA中使用Lambda的AWS DynamoDB触发器

Ioa*_*kos 4 java stream amazon-web-services amazon-dynamodb aws-lambda

我试图在dynamodb流事件上触发用Java编写的AWS lambda函数.亚马逊有一个相同的指南,在这里使用NodeJS http://docs.aws.amazon.com/lambda/latest/dg/wt-ddb-create-test-function.html

NodeJS的测试输入(来自上面的链接)看起来像一个SNS事件,所以我尝试在Java中使用相应的SNSEvent类作为我的处理程序方法的输入.

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.events.SNSEvent;
import com.amazonaws.services.lambda.runtime.events.SNSEvent.SNSRecord;
import java.util.List;

public class RecomFunction {

    public void handler(SNSEvent event, Context context) {

        LambdaLogger logger = context.getLogger();

        List<SNSRecord> records = event.getRecords();

        if (records != null) {
            for (SNSRecord record : records) {
                if (record != null) {
                    logger.log("SNS record: " + record.getSNS().getMessage());
                }
            }
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

不幸的是,record.getSNS()返回NULL导致NullPointer异常

有一个相关的问题,但没有给出具体的答案: 使用Lambda设置DynamoDB触发器

Roh*_*han 8

这段代码对我有用.您可以使用它在Lambda函数中接收和处理DynamoDB事件 -

public class Handler implements RequestHandler<DynamodbEvent, Void> {

    @Override
    public Void handleRequest(DynamodbEvent dynamodbEvent, Context context) {

        for (DynamodbStreamRecord record : dynamodbEvent.getRecords()) {

            if (record == null) {
                continue;
            }

            // Your code here
        }

        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

同样,您可以使用SNSEventSNSRecord处理Amazon SNS事件.


小智 2

创建一个接受 InputStream 的处理程序,读取 InputStream 的内容(只是 JSON),然后反序列化它以获取您需要的数据。

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.amazonaws.services.lambda.runtime.Context; 

public class MyHandler {    
    public void handler(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {           
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int letter;        
        while((letter = inputStream.read()) != -1)
        {
            baos.write(letter);                     
        }        

        //Send the contents of baos to a JSON deserializer ...          
    }      
}
Run Code Online (Sandbox Code Playgroud)

这有点麻烦,但据我所知,AWS 目前没有提供更高级别的 Java lambda 接口来使用 DynamoDB Streams。我在这里有一个完整的示例,详细介绍了如何反序列化 JSON 流以获取数据的 Java 对象。