我有几个lambda通过SNS一起工作。一个lambda接收请求并将数据发送到SNS。另一个lambda订阅了SNS。在JavaScript中很容易做,因为传入的消息只是一个JS对象。现在我将lambda重写为Java。我正在寻找在处理程序中使用的类型。
这就是lambda的样子。 SNSMessage是该类型的占位符。
public class ArchiveRequestHandler implements RequestHandler<SNSMessage?, Void> {
@Override public Void handleRequest(SNSMessage? input, Context context) {
// do something with the message
return null;
}
}
这是示例消息的样子:
{
"Records": [
{
"EventVersion": "1.0",
"EventSubscriptionArn": "arn:aws:sns:EXAMPLE",
"EventSource": "aws:sns",
"Sns": {
"SignatureVersion": "1",
"Timestamp": "1970-01-01T00:00:00.000Z",
"Signature": "EXAMPLE",
"SigningCertUrl": "EXAMPLE",
"MessageId": "1234567-ee98-5cb9-9903-4c221d41eb5e",
"Message": "Hello from SNS!",
"MessageAttributes": {
"Test": {
"Type": "String",
"Value": "TestString"
},
"TestBinary": {
"Type": "Binary",
"Value": "TestBinary"
}
},
"Type": "Notification",
"UnsubscribeUrl": "EXAMPLE",
"TopicArn": "arn:aws:sns:EXAMPLE",
"Subject": "TestInvoke"
}
}
]
}
现在我确信我可以创建自己的类型来解析它,但我希望有更标准的方法来做到这一点。但是我没有在lambda和SNS SDK依赖项中找到任何看起来像这个对象的东西。
答案 0 :(得分:7)
感谢@dnault和@notionquest的评论,我发现这个对象是aws-lambda-java-events
库的一部分。我添加了依赖项:
compile 'com.amazonaws:aws-lambda-java-events:1.3.0'
现在我可以做到:
public class ArchiveRequestHandler implements RequestHandler<SNSEvent, Void> {
@Override public Void handleRequest(SNSEvent input, Context context) {
// do something with the message
return null;
}
}
答案 1 :(得分:0)
以下Lambda代码处理SNS输入消息:
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.SNSEvent;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
public class LogEvent implements RequestHandler<SNSEvent, Object> {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
public Object handleRequest(SNSEvent request, Context context){
String timeStamp = sdf.format(new Date());
LambdaLogger logger = context.getLogger();
logger.log("-------------------------Invocation started: --------------" + timeStamp);
List<SNSEvent.SNSRecord> snsRecordList = request.getRecords();
if ( snsRecordList != null ){
SNSEvent.SNS recordSNS = null;
for ( SNSEvent.SNSRecord snsRecord : snsRecordList ) {
recordSNS = snsRecord.getSNS();
logger.log(
"Subject:[" + recordSNS.getSubject() + "]" +
"Arn:[" + recordSNS.getTopicArn() + "]" +
"attribs:[" + recordSNS.getMessageAttributes() + "]" +
"message:[" + recordSNS.getMessage() + "]" );
}//for
}
timeStamp = sdf.format(new Date());
logger.log("-------------------------Invocation completed: -------------" + timeStamp);
return null;
}
}