为什么我的 C# AWS Lambda 不发布我的 SNS 消息?

Why is my C# AWS Lambda not publishing my SNS message?

我是 C# 的新手,我正在尝试使用 Lambda 构建处理函数以将消息推送到 SNS 主题,这就是我所拥有的:

using MessagePublisher;

using Amazon.Lambda.Core;
using Amazon.SimpleNotificationService;
using Amazon.SimpleNotificationService.Model;


// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace SNSMessagePublisher
{
    public class Function
    {
        public string PublishMessageHandler(NewMessage input, ILambdaContext context)
        {
            var client = new AmazonSimpleNotificationServiceClient(Amazon.RegionEndpoint.EUWest2);
            LambdaLogger.Log($"Calling function name: {context.FunctionName}\n");
            var publishRequest = new PublishRequest(
                "arn:aws:sns:eu-west-2:123...9:TopicABC",
                input.body);
            client.PublishAsync(publishRequest);
            return $"Message Published: {input.body}";
        }
    }
}
namespace MessagePublisher {
    public class NewMessage {
        public string body { get; set; }
    }
}

然后我触发一组负载:

{
  "body": "test body"
}

并且在 CloudWatch 日志中,我得到以下输出:

Calling function name: messagePublisher

以及 Lambda 控制台 returns:

"Message Published: test body"

但是,该主题从未真正收到消息。

client.PublishAsync(publishRequest); 是异步的,将 return 变成 Task,因此,您需要使用 await 等待任务完成执行.

如果不在任务上调用 await,则无法保证客户端在 Lambda 完成执行之前已发布消息。

未发送消息,因为在 Lambda 函数 returned 之前发送消息的任务尚未完成执行。

这应该有效:

public async Task<string> PublishMessageHandler(NewMessage input, ILambdaContext context)
{
    var client = new AmazonSimpleNotificationServiceClient(Amazon.RegionEndpoint.EUWest2);
    LambdaLogger.Log($"Calling function name: {context.FunctionName}\n");
    var publishRequest = new PublishRequest(
        "arn:aws:sns:eu-west-2:123...9:TopicABC",
        input.body);
    await client.PublishAsync(publishRequest);
    return $"Message Published: {input.body}";
}

由于您是 C# 的新手,我建议您阅读 Microsoft 的 Asynchronous programming with async and await 文章。