使用 S3 事件通知 - AWS SDK for Java 2.x

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

使用 S3 事件通知

為了協助您監控儲存貯體中的活動,Amazon S3 可以在特定事件發生時傳送通知。Amazon S3 使用者指南提供儲存貯體可傳送的通知相關資訊。

您可以使用 For Java 設定值區,將事件傳送至四個可能的SDK目的地:

  • Amazon Simple Notification Service 主題

  • Amazon Simple Queue Service 佇列

  • AWS Lambda 函數

  • Amazon EventBridge

當您設定要傳送事件的值區時 EventBridge,您可以設定 EventBridge 規則,將相同事件散佈至多個目的地。當您將值區設定為直接傳送至前三個目的地之一時,每個事件只能指定一個目的地類型。

在下一節中,您將看到如何使用 For Java 設定儲存貯體,以兩種方式傳送 S3 事件通知:直接到 Amazon SQS 佇列和 EventBridge. SDK

最後一節說明如何使用 S3 事件通知API以物件導向方式處理通知。

將值區設定為直接傳送至目的地

下列範例會將值區設定為在值區發生物件建立事件或物件標記事件時傳送通知。

static void processS3Events(String bucketName, String queueArn) { // 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) ); }

上面顯示的代碼設置了一個隊列來接收兩種類型的事件。方便的是,該queueConfigurations方法允許您根據需要設置多個隊列目的地。此外,在該notificationConfiguration方法中,您可以設置其他目的地,例如一個或多個 Amazon SNS 主題或一個或多個 Lambda 函數。下列程式碼片段顯示包含兩個佇列和三種目的地類型的範例。

s3Client.putBucketNotificationConfiguration(b -> b .notificationConfiguration(ncb -> ncb .queueConfigurations(qcb -> qcb .events(Event.S3_OBJECT_CREATED, Event.S3_OBJECT_TAGGING) .queueArn(queueArn), qcb2 -> qcb2.<...>) .topicConfigurations(tcb -> tcb.<...>) .lambdaFunctionConfigurations(lfcb -> lfcb.<...>)) .bucket(bucketName) );

程式碼範例 GitHub 儲存庫包含將 S3 事件通知直接傳送至佇列的完整範例。

設定要傳送至的值區 EventBridge

下列範例會設定要傳送通知的值區。 EventBridge

public static String setBucketNotificationToEventBridge(String bucketName) { // Enable bucket to emit S3 Event notifications to EventBridge. s3Client.putBucketNotificationConfiguration(b -> b .bucket(bucketName) .notificationConfiguration(b1 -> b1 .eventBridgeConfiguration(SdkBuilder::build)) .build());

當您設定要將事件傳送至的值區時 EventBridge,您只需指定 EventBridge目的地,而不是事件類型,也不是要分派 EventBridge 到的最終目的地。您可以使用 Java SDK 的 EventBridge客戶端來配置最終目標和事件類型。

下面的代碼演示了如 EventBridge 何配置扇出對象創建的事件到一個主題和隊列。

public static String configureEventBridge(String topicArn, String queueArn) { try { // Create an EventBridge rule to route Object Created notifications. PutRuleRequest putRuleRequest = PutRuleRequest.builder() .name(RULE_NAME) .eventPattern(""" { "source": ["aws.s3"], "detail-type": ["Object Created"], "detail": { "bucket": { "name": ["%s"] } } } """.formatted(bucketName)) .build(); // Add the rule to the default event bus. PutRuleResponse putRuleResponse = eventBridgeClient.putRule(putRuleRequest) .whenComplete((r, t) -> { if (t != null) { logger.error("Error creating event bus rule: " + t.getMessage(), t); throw new RuntimeException(t.getCause().getMessage(), t); } logger.info("Event bus rule creation request sent successfully. ARN is: {}", r.ruleArn()); }).join(); // Add the existing SNS topic and SQS queue as targets to the rule. eventBridgeClient.putTargets(b -> b .eventBusName("default") .rule(RULE_NAME) .targets(List.of ( Target.builder() .arn(queueArn) .id("Queue") .build(), Target.builder() .arn(topicArn) .id("Topic") .build()) ) ).join(); return putRuleResponse.ruleArn(); } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return null; }

要使用 Java 代碼,請將對工件的依賴項添加到 Maven pom.xml 文件 EventBridge 中。eventbridge

<dependency> <groupId>software.amazon.awssdk</groupId> <artifactId>eventbridge</artifactId> </dependency>

程式碼範例 GitHub 儲存庫包含將 S3 事件通知傳送至主題 EventBridge 和佇列,然後傳送至主題和佇列的完整範例。

使用 S3 事件通知API處理事件

目的地收到 S3 通知事件後,您可以使用 S3 事件通知API以物件導向方式處理事件。您可以使用 S3 事件通知API來處理直接傳送至目標的事件通知 (如第一個範例所示),但不會使用路由傳送的通知 EventBridge。儲存貯體傳送的 S3 事件通知,其中 EventBridge 包含 S3 事件通知目前未處理的API不同結構

新增相依性

S3 事件通知API已隨著適用SDK於 Java 2.x 版的 2.25.11 版發行。

要使用 S3 事件通知API,請將所需的依賴元素添加到您的 Maven,pom.xml如下面的代碼片段。

<dependencyManagement> <dependencies> <dependency> <groupId>software.amazon.awssdk</groupId> <artifactId>bom</artifactId> <version>2.X.X1</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>software.amazon.awssdk</groupId> <artifactId>s3-event-notifications</artifactId> </dependency> </dependencies>

1 最新版本

使用S3EventNotification

從JSON字符串創建一個S3EventNotification實例

若要將字JSON串轉換成S3EventNotification物件,請使用S3EventNotification類別的靜態方法,如下列範例所示。

import software.amazon.awssdk.eventnotifications.s3.model.S3EventNotification import software.amazon.awssdk.eventnotifications.s3.model.S3EventNotificationRecord import software.amazon.awssdk.services.sqs.model.Message; public class S3EventNotificationExample { ... void receiveMessage(Message message) { // Message received from SQSClient. String sqsEventBody = message.body(); S3EventNotification s3EventNotification = S3EventNotification.fromJson(sqsEventBody); // Use getRecords() to access all the records in the notification. List<S3EventNotificationRecord> records = s3EventNotification.getRecords(); S3EventNotificationRecord record = records.stream().findFirst(); // Use getters on the record to access individual attributes. String awsRegion = record.getAwsRegion(); String eventName = record.getEventName(); String eventSource = record.getEventSource(); } }

在此範例中,方fromJson法會將字JSON串轉換為S3EventNotification物件。JSON字串中缺少欄位將導致對應 Java 物件欄位中的null值,而且JSON會忽略中的任何額外欄位。

您可以在APIs的API參考中找到事件通知記錄的其他S3EventNotificationRecord

S3EventNotification實例轉換為字JSON符串

使用 toJson (或toJsonPretty) 方法將S3EventNotification物件轉換成JSON字串,如下列範例所示。

import software.amazon.awssdk.eventnotifications.s3.model.S3EventNotification public class S3EventNotificationExample { ... void toJsonString(S3EventNotification event) { String json = event.toJson(); String jsonPretty = event.toJsonPretty(); System.out.println("JSON: " + json); System.out.println("Pretty JSON: " + jsonPretty); } }

GlacierEventDataReplicationEventDataIntelligentTieringEventData、和的欄位LifecycleEventData會從 (JSON如果是) 中排除null。其他null字段將被序列化為null

以下顯示 S3 物件標記事件之toJsonPretty方法的範例輸出。

{ "Records" : [ { "eventVersion" : "2.3", "eventSource" : "aws:s3", "awsRegion" : "us-east-1", "eventTime" : "2024-07-19T20:09:18.551Z", "eventName" : "ObjectTagging:Put", "userIdentity" : { "principalId" : "AWS:XXXXXXXXXXX" }, "requestParameters" : { "sourceIPAddress" : "XXX.XX.XX.XX" }, "responseElements" : { "x-amz-request-id" : "XXXXXXXXXXXX", "x-amz-id-2" : "XXXXXXXXXXXXX" }, "s3" : { "s3SchemaVersion" : "1.0", "configurationId" : "XXXXXXXXXXXXX", "bucket" : { "name" : "DOC-EXAMPLE-BUCKET", "ownerIdentity" : { "principalId" : "XXXXXXXXXXX" }, "arn" : "arn:aws:s3:::XXXXXXXXXX" }, "object" : { "key" : "akey", "size" : null, "eTag" : "XXXXXXXXXX", "versionId" : null, "sequencer" : null } } } ] }

中提供了一個完整 GitHub 的範例,說明如何使用API來處理 Amazon SQS 佇列收到的通知。