AWS SNS:如何向主题发送消息?

问题描述 投票:0回答:1

我使用此代码进行发送,但在执行过程中它无限期地挂在 PublishAsync 上。 是什么原因?怎么解决?

using System;

using Amazon.SimpleNotificationService;
using Amazon.SimpleNotificationService.Model;
using System.Threading.Tasks;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = new AmazonSimpleNotificationServiceClient(Amazon.RegionEndpoint.USEast2);
            SendMessage(client).Wait();
        }

        static async Task SendMessage(IAmazonSimpleNotificationService snsClient)
        {
            var request = new PublishRequest
            {
                TopicArn = "INSERT TOPIC ARN",
                Message = "Test Message"
            };

            await snsClient.PublishAsync(request);
        }
    }
amazon-web-services amazon-sns
1个回答
0
投票

这个 .NET 代码看起来不错。我刚刚在 Visual Studio 中执行了这段 C# 代码,它运行良好。

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX - License - Identifier: Apache - 2.0

namespace PublishToSNSTopicExample
{
    // snippet-start:[SNS.dotnetv3.PublishToSNSTopicExample]
    using System;
    using System.Threading.Tasks;
    using Amazon.SimpleNotificationService;
    using Amazon.SimpleNotificationService.Model;

    /// <summary>
    /// This example publishes a message to an Amazon Simple Notification
    /// Service (Amazon SNS) topic. The code uses the AWS SDK for .NET and
    /// .NET Core 5.0.
    /// </summary>
    public class PublishToSNSTopic
    {
        public static async Task Main()
        {
            string topicArn = "arn:aws:sns:us-east-1:814548047983:scott1111";
            string messageText = "This is an example message to publish to the ExampleSNSTopic.";

            IAmazonSimpleNotificationService client = new AmazonSimpleNotificationServiceClient();

            await PublishToTopicAsync(client, topicArn, messageText);
        }

        /// <summary>
        /// Publishes a message to an Amazon SNS topic.
        /// </summary>
        /// <param name="client">The initialized client object used to publish
        /// to the Amazon SNS topic.</param>
        /// <param name="topicArn">The ARN of the topic.</param>
        /// <param name="messageText">The text of the message.</param>
        public static async Task PublishToTopicAsync(
            IAmazonSimpleNotificationService client,
            string topicArn,
            string messageText)
        {
            var request = new PublishRequest
            {
                TopicArn = topicArn,
                Message = messageText,
            };

            var response = await client.PublishAsync(request);

            Console.WriteLine($"Successfully published message ID: {response.MessageId}");
        }
    }
    // snippet-end:[SNS.dotnetv3.PublishToSNSTopicExample]
}

检查主题的 ARN 并检查您的网络连接。 .NET 代码可以工作。您可以在 AWS 代码库中找到该服务的此示例和其他示例。

使用适用于 .NET 的 AWS 开发工具包的 Amazon SNS 示例

© www.soinside.com 2019 - 2024. All rights reserved.