无法在C#中访问Amazon SQS消息属性

我有一个创建SQS消息并将它们放在SQS队列上的进程,以及另一个读取这些消息并根据正文内容和消息属性执行某些逻辑的进程。

我可以使用正文和属性在SQS队列上成功创建消息,但是在阅读消息属性时我遇到了问题!

我确信我的消息创建过程是正确的,我可以在AWS SQS控制台中看到队列的属性。 我只是想不通为什么我不能读回那些属性。

我创建消息的代码:

IAmazonSQS sqs = AWSClientFactory.CreateAmazonSQSClient(); var sendMessageRequest = new SendMessageRequest(); sendMessageRequest.QueueUrl = "myURL"; Dictionary MessageAttributes = new Dictionary(); MessageAttributeValue messageTypeAttribute = new MessageAttributeValue(); messageTypeAttribute.DataType = "String"; messageTypeAttribute.StringValue = "HIGH"; MessageAttributes.Add("MESSAGEPRIORITY", messageTypeAttribute); sendMessageRequest.MessageAttributes = MessageAttributes; sendMessageRequest.MessageBody = "Thats the message body"; sqs.SendMessage(sendMessageRequest); 

创建了上述工作和属性为MESSAGEPRIORITY = HIGH的消息(我可以在SQS控制台中看到消息和属性)。

回读消息时(我已经跳过显示队列URL等的部分代码):

 IAmazonSQS sqs = AWSClientFactory.CreateAmazonSQSClient(); ReceiveMessageResponse receiveMessage = new ReceiveMessageResponse(); ReceiveMessageRequest request = new ReceiveMessageRequest(); request.QueueUrl = "myURL"; receiveMessage = sqs.ReceiveMessage(request); string messageBody = receiveMessage.Messages[0].Body; Dictionary messageAttributes = receiveMessage.Messages[0].MessageAttributes; 

使用上面的代码,我得到了消息的正文,但属性是空的! 我直接使用SQS队列手动创建消息时遇到同样的问题。 我弄不清楚为什么? 任何帮助都会很棒。 非常感谢,

好的,所以我想出了这一个。 在调用拉取消息之前,需要将属性名称指定为ReceiveMessageRequest对象的属性。

因此,上面的代码需要更改为:

 IAmazonSQS sqs = AWSClientFactory.CreateAmazonSQSClient(); ReceiveMessageResponse receiveMessage = new ReceiveMessageResponse(); ReceiveMessageRequest request = new ReceiveMessageRequest(); //Specify attribute list List AttributesList = new List(); AttributesList.Add("MESSAGEPRIORITY"); //Assign list and QueueURL to request request.MessageAttributeNames = AttributesList; request.QueueUrl = "myURL"; //Receive the message... receiveMessage = sqs.ReceiveMessage(request); //Body... string messageBody = receiveMessage.Messages[0].Body; //...and attributes Dictionary messageAttributes = receiveMessage.Messages[0].MessageAttributes; 

以上对我有用。 希望它对某人有用….

要检索消息的所有属性而不指定每个属性,可以在属性列表中放置“*”或“All”。 像这样:

 //Specify attribute list List AttributesList = new List(); AttributesList.Add("*"); 

AWS SQS ReceiveMessage文档