本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
將訊息屬性傳送至 Amazon SQS 佇列
您可使用訊息屬性提供有關訊息的結構化中繼資料項目 (例如,時間戳記、地理空間資料、簽章和識別碼)。如需詳細資訊,請參閱Amazon SQS 訊息屬性。
執行範例程式碼之前,請確定您已設定 AWS 登入資料。如需詳細資訊,請參閱《 AWS SDK for Java 2.x 開發人員指南》中的設定開發的 AWS 登入資料和區域。
定義屬性
為了定義訊息的屬性,請新增以下使用 MessageAttributeValue 資料類型的程式碼。如需詳細資訊,請參閱訊息屬性元件及訊息屬性資料類型。
AWS SDK for Java 會自動計算訊息內文和訊息屬性檢查總和,並將其與 Amazon SQS 傳回的資料進行比較。如需詳細資訊,請參閱 AWS SDK for Java 2.x 開發人員指南以及適用於其他程式設計語言的 計算訊息屬性的 MD5 訊息摘要。
- String
-
此範例將名為 Name 的 String 屬性定義為 Jane 的值。
final Map<String, MessageAttributeValue> messageAttributes = new HashMap<>();
messageAttributes.put("Name", new MessageAttributeValue()
.withDataType("String")
.withStringValue("Jane"));
- Number
-
此範例將名為 AccurateWeight 的 Number 屬性定義為 230.000000000000000001 的值。
final Map<String, MessageAttributeValue> messageAttributes = new HashMap<>();
messageAttributes.put("AccurateWeight", new MessageAttributeValue()
.withDataType("Number")
.withStringValue("230.000000000000000001"));
- Binary
-
此範例將名為 ByteArray 的 Binary 屬性定義為未初始化 10 位元組陣列的值。
final Map<String, MessageAttributeValue> messageAttributes = new HashMap<>();
messageAttributes.put("ByteArray", new MessageAttributeValue()
.withDataType("Binary")
.withBinaryValue(ByteBuffer.wrap(new byte[10])));
- String (custom)
-
此範例將名為 EmployeeId 的自訂屬性 String.EmployeeId 定義為 ABC123456 的值。
final Map<String, MessageAttributeValue> messageAttributes = new HashMap<>();
messageAttributes.put("EmployeeId", new MessageAttributeValue()
.withDataType("String.EmployeeId")
.withStringValue("ABC123456"));
- Number (custom)
-
此範例將名為 AccountId 的自訂屬性 Number.AccountId 定義為 000123456 的值。
final Map<String, MessageAttributeValue> messageAttributes = new HashMap<>();
messageAttributes.put("AccountId", new MessageAttributeValue()
.withDataType("Number.AccountId")
.withStringValue("000123456"));
- Binary (custom)
-
此範例將名為 ApplicationIcon 的自訂屬性 Binary.JPEG 定義為未初始化 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);