使用以接收和處理 Amazon S3 事件通知 AWS SDK. - Amazon Simple Storage Service

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

使用以接收和處理 Amazon S3 事件通知 AWS SDK.

下列程式碼範例顯示如何以物件導向方式處理 S3 事件通知。

Java
SDK對於爪哇 2.x
注意

還有更多關於 GitHub。尋找完整範例,並瞭解如何在 AWS 代碼示例存儲庫

此範例顯示如何使用 Amazon 處理 S3 通知事件SQS。

/** * This method receives S3 event notifications by using an SqsAsyncClient. * After the client receives the messages it deserializes the JSON payload and logs them. It uses * the S3EventNotification class (part of the S3 event notification API for Java) to deserialize * the JSON payload and access the messages in an object-oriented way. * * @param queueUrl The URL of the AWS SQS queue that receives the S3 event notifications. * @see <a href="https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/eventnotifications/s3/model/package-summary.html">S3EventNotification API</a>. * <p> * To use S3 event notification serialization/deserialization to objects, add the following * dependency to your Maven pom.xml file. * <dependency> * <groupId>software.amazon.awssdk</groupId> * <artifactId>s3-event-notifications</artifactId> * <version><LATEST></version> * </dependency> * <p> * The S3 event notification API became available with version 2.25.11 of the Java SDK. * <p> * This example shows the use of the API with AWS SQS, but it can be used to process S3 event notifications * in AWS SNS or AWS Lambda as well. * <p> * Note: The S3EventNotification class does not work with messages routed through AWS EventBridge. */ static void processS3Events(String bucketName, String queueUrl, String queueArn) { try { // Configure the bucket to send Object Created and Object Tagging notifications to an existing SQS queue. s3Client.putBucketNotificationConfiguration(b -> b .notificationConfiguration(ncb -> ncb .queueConfigurations(qcb -> qcb .events(Event.S3_OBJECT_CREATED, Event.S3_OBJECT_TAGGING) .queueArn(queueArn))) .bucket(bucketName) ).join(); triggerS3EventNotifications(bucketName); // Wait for event notifications to propagate. Thread.sleep(Duration.ofSeconds(5).toMillis()); boolean didReceiveMessages = true; while (didReceiveMessages) { // Display the number of messages that are available in the queue. sqsClient.getQueueAttributes(b -> b .queueUrl(queueUrl) .attributeNames(QueueAttributeName.APPROXIMATE_NUMBER_OF_MESSAGES) ).thenAccept(attributeResponse -> logger.info("Approximate number of messages in the queue: {}", attributeResponse.attributes().get(QueueAttributeName.APPROXIMATE_NUMBER_OF_MESSAGES))) .join(); // Receive the messages. ReceiveMessageResponse response = sqsClient.receiveMessage(b -> b .queueUrl(queueUrl) ).get(); logger.info("Count of received messages: {}", response.messages().size()); didReceiveMessages = !response.messages().isEmpty(); // Create a collection to hold the received message for deletion // after we log the messages. HashSet<DeleteMessageBatchRequestEntry> messagesToDelete = new HashSet<>(); // Process each message. response.messages().forEach(message -> { logger.info("Message id: {}", message.messageId()); // Deserialize JSON message body to a S3EventNotification object // to access messages in an object-oriented way. S3EventNotification event = S3EventNotification.fromJson(message.body()); // Log the S3 event notification record details. if (event.getRecords() != null) { event.getRecords().forEach(record -> { String eventName = record.getEventName(); String key = record.getS3().getObject().getKey(); logger.info(record.toString()); logger.info("Event name is {} and key is {}", eventName, key); }); } // Add logged messages to collection for batch deletion. messagesToDelete.add(DeleteMessageBatchRequestEntry.builder() .id(message.messageId()) .receiptHandle(message.receiptHandle()) .build()); }); // Delete messages. if (!messagesToDelete.isEmpty()) { sqsClient.deleteMessageBatch(DeleteMessageBatchRequest.builder() .queueUrl(queueUrl) .entries(messagesToDelete) .build() ).join(); } } // End of while block. } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } }

有關的完整列表 AWS SDK開發人員指南和代碼示例,請參閱搭配 AWS SDK 使用此服務。本主題也包含有關入門的資訊以及舊SDK版的詳細資訊。