Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门。本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
发送消息属性
使用消息可将结构化元数据(如时间戳、地理空间数据、签名和标识符)与消息包括在消息中使消息属性. 有关更多信息,请参阅 Amazon SQS 消息属性。
运行示例代码之前,请确保您设置了Amazon凭证。有关更多信息,请参阅 。设置Amazon发展凭证和区域中的Amazon SDK for Java 2.x开发人员指南.
定义属性
要定义消息属性,请添加以下代码,其中使用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"));
- 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);