將訊息屬性傳送至 Amazon SQS 佇列 - Amazon Simple Queue Service

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

將訊息屬性傳送至 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

此範例將名為 NameString 屬性定義為 Jane 的值。

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

此範例將名為 AccurateWeightNumber 屬性定義為 230.000000000000000001 的值。

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

此範例將名為 ByteArrayBinary 屬性定義為未初始化 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"));
注意

由於基本資料類型為 NumberReceiveMessage 動作會傳回 123456

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);
重要

如果您將訊息傳送到 先進先出 (FIFO) 佇列,請確保 sendMessage 方法在您提供訊息群組 ID 之後才執行。

如果您使用 SendMessageBatch 方法,而非 SendMessage,您必須為批次中每個訊息指定訊息屬性。