订阅者如何只收到一次消息

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

我有两个应用程序,一个用于发布消息,一个用于接收消息。我的问题是有没有一种方法可以确保订阅者应用程序的每个用户仅收到该消息一次。当我运行该应用程序时,它每次都会显示相同的消息。以下是我的应用程序的代码: 发布者申请: 程序.cs

using Amazon;
using Amazon.Runtime;
using Amazon.SimpleNotificationService;
using Publisher;

var awsCredentials = new BasicAWSCredentials("Some_KEY", "Some_KEY");
var snsClient = new AmazonSimpleNotificationServiceClient(awsCredentials, RegionEndpoint.USEast1);

var publisher = new SnsPublisher(snsClient);
var customerCreated = new CustomerCreated
{
    Id = 1,
    FullName = "John Doe",
    MessageTypeName = "CustomerCreated"
};

await publisher.PublishAsync("arn:aws:sns:us-east-1:xxxxxxxxxxxxx:first_notification_test", customerCreated);

namespace Publisher
{
    public class CustomerCreated : IMessage
    {
        public int Id {  get; set; }
        public string FullName { get; set; }

        public string MessageTypeName { get; set; }
    }
}

订阅者应用程序(WPF 应用程序):

namespace WpfApp1
{
    public partial class App : Application
    {
        private AmazonSimpleNotificationServiceClient snsClient;
        private AmazonSQSClient sqsClient;
        private string queueUrl;
        private CancellationTokenSource cancellationTokenSource;
        private readonly List<string> _messageAttributeNames = new() { "All" };

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            var credentials = new BasicAWSCredentials("some_key", "some_key");
            sqsClient = new AmazonSQSClient(credentials, RegionEndpoint.USEast1);

            // Subscribe SQS queue to SNS topic
            SubscribeSqsQueueToSnsTopicAsync("arn:aws:sns:us-east-1:xxxxxxxxxxxxxx:first_notification_test", "https://sqs.us-east-1.amazonaws.com/xxxxxxxxxxx/test-queue");

            // Start polling SQS queue for messages
            cancellationTokenSource = new CancellationTokenSource();
            Task.Run(() => PollSqsQueueForMessages(cancellationTokenSource.Token));
        }

        private async Task SubscribeSqsQueueToSnsTopicAsync(string topicArn, string queueUrl)
        {
            var receiveRequest = new ReceiveMessageRequest
            {
                MessageAttributeNames = _messageAttributeNames,
                AttributeNames = _messageAttributeNames,
                QueueUrl = queueUrl
            };

            var messageResponse = await sqsClient.ReceiveMessageAsync(receiveRequest);
        }
amazon-sqs amazon-sns
1个回答
0
投票

听起来你也可以通过幂等性来解决问题

您可以查看重复数据删除 ID 属性以在客户端中实现幂等性。

https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/using-messageseduplicationid-property.html

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