向 Amazon SQS 队列发送消息属性 - Amazon Simple Queue Service
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

向 Amazon SQS 队列发送消息属性

您可以使用消息属性,在消息中包括结构化元数据(如时间戳、地理空间数据、签名和标识符)。有关更多信息,请参阅 Amazon SQS 消息属性

在运行示例代码之前,请确保已设置 Amazon 凭据。有关更多信息,请参阅《Amazon SDK for Java 2.x 开发人员指南》中的设置开发 Amazon 凭证和区域

定义属性

要为消息定义属性,请添加使用 MessageAttributeValue 数据类型的以下代码。有关更多信息,请参阅 消息属性组件消息属性数据类型

会 Amazon SDK for Java 自动计算消息正文和消息属性的校验和,并将它们与 Amazon SQS 返回的数据进行比较。有关更多信息,请参阅 Amazon SDK for Java 2.x 开发人员指南;有关其他编程语言,请参阅计算消息属性的 MD5 消息摘要

String

此示例定义 String 属性,其名称为 Name,值为 Jane

final Map<String, MessageAttributeValue> messageAttributes = new HashMap<>(); messageAttributes.put("Name", new MessageAttributeValue() .withDataType("String") .withStringValue("Jane"));
Number

此示例定义 Number 属性,其名称为 AccurateWeight,值为 230.000000000000000001

final Map<String, MessageAttributeValue> messageAttributes = new HashMap<>(); messageAttributes.put("AccurateWeight", new MessageAttributeValue() .withDataType("Number") .withStringValue("230.000000000000000001"));
Binary

此示例定义 Binary 属性,其名称为 ByteArray,值为未初始化的 10 字节数组。

final Map<String, MessageAttributeValue> messageAttributes = new HashMap<>(); messageAttributes.put("ByteArray", new MessageAttributeValue() .withDataType("Binary") .withBinaryValue(ByteBuffer.wrap(new byte[10])));
String (custom)

此示例定义自定义属性 String.EmployeeId,其名称为 EmployeeId,值为 ABC123456

final Map<String, MessageAttributeValue> messageAttributes = new HashMap<>(); messageAttributes.put("EmployeeId", new MessageAttributeValue() .withDataType("String.EmployeeId") .withStringValue("ABC123456"));
Number (custom)

此示例定义自定义属性 Number.AccountId,其名称为 AccountId,值为 000123456

final Map<String, MessageAttributeValue> messageAttributes = new HashMap<>(); messageAttributes.put("AccountId", new MessageAttributeValue() .withDataType("Number.AccountId") .withStringValue("000123456"));
注意

由于基本数据类型为 NumberReceiveMessage 方法会返回 123456

Binary (custom)

此示例定义自定义属性 Binary.JPEG,其名称为 ApplicationIcon,值为未初始化的 10 字节数组。

final Map<String, MessageAttributeValue> messageAttributes = new HashMap<>(); messageAttributes.put("ApplicationIcon", new MessageAttributeValue() .withDataType("Binary.JPEG") .withBinaryValue(ByteBuffer.wrap(new byte[10])));

发送带有属性的消息

此示例在发送消息之前将属性添加到 SendMessageRequest 中。

// Send a message with an attribute. final SendMessageRequest sendMessageRequest = new SendMessageRequest(); sendMessageRequest.withMessageBody("This is my message text."); sendMessageRequest.withQueueUrl(myQueueUrl); sendMessageRequest.withMessageAttributes(messageAttributes); sqs.sendMessage(sendMessageRequest);
重要

如果将消息发送到先进先出 (FIFO) 队列,请确保 sendMessage 方法在提供消息组 ID 之后执行。

如果您使用 SendMessageBatch 方法而非 SendMessage,则必须指定批处理中每条消息的消息属性。