我想从Lambda函数调用中发布一些数据到SNS,但似乎并没有起作用。我的函数代码是 -
public class Handler implements RequestHandler<DynamodbEvent, Void> {
private static final String SNS_TOPIC_ARN = "arn:aws:sns:us-west-2:account_number:function_name";
@Override
public Void handleRequest(DynamodbEvent dynamodbEvent, Context context) {
LambdaLogger logger = context.getLogger();
AmazonSNSClient snsClient = new AmazonSNSClient(new DefaultAWSCredentialsProviderChain());
snsClient.setRegion(Region.getRegion(Regions.US_WEST_2));
for (DynamodbStreamRecord record : dynamodbEvent.getRecords()) {
Map<String, AttributeValue> newImage = record.getDynamodb().getNewImage();
if (newImage == null) {
continue;
}
String sensorId = newImage.get("sensorID").getS();
long timestamp = Long.parseLong(newImage.get("timestamp").getS());
double temperature = Double.parseDouble(newImage.get("payload").getM().get("temp").getN());
String data = sensorId + " " + timestamp + " " + temperature;
logger.log(data);
PublishRequest publishRequest = new PublishRequest(SNS_TOPIC_ARN, data);
PublishResult publishResult = snsClient.publish(publishRequest);
logger.log("Publish Successful " + publishResult.getMessageId());
}
snsClient.shutdown();
return null;
}
}
这个调用导致超时(10秒),Lambda函数执行失败。如果我注释掉SNS发布部分,也就是说,如果我只记录从DynamoDB接收到的数据,它就可以正常工作。一旦添加了SNS发布代码,它就会超时。
在CloudWatch中记录的超时消息为 -
START RequestId: 8db74187-459b-42c5-8a06-b3a74873b236 Version: $LATEST
END RequestId: 8db74187-459b-42c5-8a06-b3a74873b236
REPORT RequestId: 8db74187-459b-42c5-8a06-b3a74873b236 Duration: 10001.66 ms Billed Duration: 10000 ms Memory Size: 128 MB Max Memory Used: 37 MB
Task timed out after 10.00 seconds
我已经设置了所有必要的权限,并且可以使用以下代码在我的PC上发布到SNS -
PublishRequest publishRequest = new PublishRequest(SNS_TOPIC_ARN, data);
PublishResult publishResult = snsClient.publish(publishRequest);
System.out.println("Publish Successful " + publishResult.getMessageId());
我还尝试使用 AmazonSNSAsyncClient
而不是 AmazonSNSClient
,但结果相同。
我错过了什么?
logger.log()
(记录接收到的数据的函数)也没有被执行到。 - Rohan