本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
下列程式碼範例顯示如何實作 Lambda 函數,以便接收在收到來自 SNS 主題的訊息時觸發的事件。函數會從事件參數擷取訊息,並記錄每一則訊息的內容。
- AWS SDK for .NET
-
注意
GitHub 上提供更多範例。尋找完整範例,並了解如何在無伺服器範例
儲存庫中設定和執行。 使用 .NET 搭配 Lambda 來使用 SNS 事件。
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using Amazon.Lambda.Core; using Amazon.Lambda.SNSEvents; // 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 SnsIntegration; public class Function { public async Task FunctionHandler(SNSEvent evnt, ILambdaContext context) { foreach (var record in evnt.Records) { await ProcessRecordAsync(record, context); } context.Logger.LogInformation("done"); } private async Task ProcessRecordAsync(SNSEvent.SNSRecord record, ILambdaContext context) { try { context.Logger.LogInformation($"Processed record {record.Sns.Message}"); // TODO: Do interesting work based on the new message await Task.CompletedTask; } catch (Exception e) { //You can use Dead Letter Queue to handle failures. By configuring a Lambda DLQ. context.Logger.LogError($"An error occurred"); throw; } } }
如需 AWS SDK 開發人員指南和程式碼範例的完整清單,請參閱 搭配 AWS SDK 使用 Lambda。此主題也包含有關入門的資訊和舊版 SDK 的詳細資訊。