

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# S3 イベント通知の使用
<a name="examples-s3-event-notifications"></a>

バケット内のアクティビティのモニタリングに向けて、Amazon S3 は特定のイベントが発生したときに通知を送信できます。Amazon S3 ユーザーガイドには、[バケットが送信できる通知](https://docs.aws.amazon.com/AmazonS3/latest/userguide/EventNotifications.html#notification-how-to-overview)に関する情報が記載されています。

SDK for Java を使用して、4 つの送信先にイベントを送信するようにバケットを設定できます。
+ Amazon Simple Notification Service トピック
+ Amazon Simple Queue Service キュー
+ AWS Lambda 関数
+ Amazon EventBridge

EventBridge にイベントを送信するようにバケットを設定すると、同じイベントを複数の送信先にファンアウトするように EventBridge ルールを設定できます。最初の 3 つの送信先のいずれかに直接送信するようにバケットを設定する場合、イベントごとに指定できる送信先タイプは 1 つだけです。

次のセクションでは、SDK for Java を使用してバケットを設定し、Amazon SQS キューと EventBridge の 2 つの送信先に S3 イベント通知を送信する方法について説明します。

最後のセクションでは、S3 イベント通知 API を使用して、オブジェクト指向の方法で通知を使用する方法を示します。

## 送信先に直接送信するようにバケットを設定する
<a name="s3-event-conf-bucket-direct"></a>

次の例では、*オブジェクトの作成*イベントまたは*オブジェクトのタグ付け*イベントがバケットに対して発生したときに通知を送信するようにバケットを設定します。

```
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)
    );
}
```

上記のコードは、2 種類のイベントを受信するように 1 つのキューを設定します。`queueConfigurations` メソッドを使用すると、必要に応じて複数のキューの送信先を設定できるため、便利です。また、 `notificationConfiguration` メソッドでは、1 つ以上の Amazon SNS トピックや 1 つ以上の Lambda 関数など、追加の送信先を設定できます。次のスニペットは、2 つのキューと 3 種類の送信先を含む例を示しています。

```
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)
        );
```

「Code Examples」の GitHub リポジトリには、S3 イベント通知をキューに直接送信するための[完全な例](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javav2/example_code/s3/src/main/java/com/example/s3/ProcessS3EventNotification.java)が記載されています。

## EventBridge に送信するようにバケットを設定する
<a name="s3-event-conf-bucket-eventbridge"></a>

次の例では、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 コードで EventBridge を使用するには、Maven `pom.xml` ファイルに `eventbridge` アーティファクトの依存関係を追加します。

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

「Code Examples」の GitHub リポジトリには、S3 イベント通知を EventBridge に送信し、その後トピックとキューに送信するための[完全な例](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javav2/example_code/s3/src/main/java/com/example/s3/PutBucketS3EventNotificationEventBridge.java)が記載されています。

## S3 イベント通知 API を使用してイベントを処理する
<a name="s3-event-notification-read"></a>

送信先が S3 通知イベントを受信したら、S3 イベント通知 API を使用して、オブジェクト指向の方法でイベントを処理できます。S3 イベント通知 API を使用して、ターゲットに直接ディスパッチされるイベント通知 ([最初の例](#s3-event-conf-bucket-direct)を参照) を使用できますが、EventBridge 経由でルーティングされる通知は使用できません。バケットから EventBridge に送信される S3 イベント通知には、S3 イベント通知 API が現在対応していない[別の構造](https://docs.aws.amazon.com/AmazonS3/latest/userguide/ev-events.html#ev-events-list)が含まれています。

### 依存関係を追加する
<a name="s3-event-notifications-dep"></a>

S3 イベント通知 API は、SDK for 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 [最新バージョン](https://central.sonatype.com/artifact/software.amazon.awssdk/bom)。

### `S3EventNotification` クラスを使用する
<a name="s3-event-notifications-use"></a>

#### JSON 文字列から `S3EventNotification` インスタンスを作成する
<a name="s3-event-notifications-use-from-json"></a>

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 に余分なフィールドが含まれていても無視されます。

イベント通知レコードの他の API は、`[S3EventNotificationRecord](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/eventnotifications/s3/model/S3EventNotificationRecord.html)` の API リファレンスに記載されています。

#### `S3EventNotification` インスタンスを JSON 文字列に変換する
<a name="s3-event-notifications-use-to-json"></a>

次の例に示すように、 `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);
    }
}
```

`GlacierEventData`、`ReplicationEventData`、`IntelligentTieringEventData`、および `LifecycleEventData` のフィールドは、`null` の場合は JSON から除外されます。他の `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" : "amzn-s3-demo-bucket",
        "ownerIdentity" : {
          "principalId" : "XXXXXXXXXXX"
        },
        "arn" : "arn:aws:s3:::XXXXXXXXXX"
      },
      "object" : {
        "key" : "akey",
        "size" : null,
        "eTag" : "XXXXXXXXXX",
        "versionId" : null,
        "sequencer" : null
      }
    }
  } ]
}
```

GitHub には、API を使用して Amazon SQS キューによって受信された通知を使用する方法を示す[完全な例](https://github.com/awsdocs/aws-doc-sdk-examples/blob/75c3daadf750406156fc87fa30ee499a206b4a36/javav2/example_code/s3/src/main/java/com/example/s3/ProcessS3EventNotification.java#L117)があります。

## Java ライブラリを使用して Lambda で S3 イベントを処理する: AWS SDK for Java 2.x および `aws-lambda-java-events`
<a name="s3-event-notif-processing-options"></a>

SDK for Java 2.x を使用して Lambda 関数で Amazon S3 イベント通知を処理する代わりに、バージョン 3.x.x. AWS `[aws-lambda-java-events](https://github.com/aws/aws-lambda-java-libs/tree/main/aws-lambda-java-events)`の`aws-lambda-java-events`ライブラリを個別に維持し、独自の依存要件があります。`aws-lambda-java-events` ライブラリは Lambda 関数の S3 イベントでのみ動作しますが、SDK for Java 2.x は Lambda 関数、Amazon SNS、Amazon SQS の S3 イベントで動作します。

どちらのアプローチも、オブジェクト指向の方法で JSON のイベント通知ペイロードをモデル化し、類似した API を提供します。次の表は、2 つのアプローチの使用における顕著な違いを示しています。


****  

|  | AWS SDK for Java | aws-lambda-java-events ライブラリ | 
| --- | --- | --- | 
| パッケージの命名 |  `software.amazon.awssdk.eventnotifications.s3.model.S3EventNotification`  | com.amazonaws.services.lambda.runtime.events.models.s3.S3EventNotification | 
| RequestHandler パラメータ |  Lambda 関数の `RequestHandler` 実装を記述して JSON 文字列を受け取ります。 <pre>import com.amazonaws.services.lambda.runtime.Context;<br />import com.amazonaws.services.lambda.runtime.RequestHandler;<br />import software.amazon.awssdk.eventnotifications.s3.model.S3EventNotification;<br /><br />public class Handler implements RequestHandler<String, String> {<br /><br />    @Override<br />        public String handleRequest(String jsonS3Event, Context context) {<br />            S3EventNotification s3Event = S3EventNotification<br />                                             .fromJson(jsonS3Event);<br />            // Work with the s3Event object.        <br />            ...<br />    }<br />}</pre>  | Lambda 関数の RequestHandler 実装を記述して S3Event オブジェクトを受け取ります。<pre>import com.amazonaws.services.lambda.runtime.Context;<br />import com.amazonaws.services.lambda.runtime.RequestHandler;<br />import com.amazonaws.services.lambda.runtime.events.S3Event;<br /><br />public class Handler implements RequestHandler<S3Event, String> {<br /><br />    @Override<br />        public String handleRequest(S3Event s3event, Context context) {<br />            // Work with the s3Event object.        <br />            ...<br />    }<br />}</pre> | 
| Maven の依存関係 |  <pre><dependencyManagement><br />    <dependencies><br />        <dependency><br />            <groupId>software.amazon.awssdk</groupId><br />            <artifactId>bom</artifactId><br />            <version>2.X.X</version><br />            <type>pom</type><br />            <scope>import</scope><br />        </dependency><br />    </dependencies><br /></dependencyManagement><br /><dependencies><br />    <dependency><br />        <groupId>software.amazon.awssdk</groupId><br />        <artifactId>s3-event-notifications</artifactId><br />    </dependency><br />    <!-- Add other SDK dependencies that you need. --><br /></dependencies></pre>  |  <pre><dependencyManagement><br />    <dependencies><br />        <dependency><br />            <groupId>software.amazon.awssdk</groupId><br />            <artifactId>bom</artifactId><br />            <version>2.X.X</version><br />            <type>pom</type><br />            <scope>import</scope><br />        </dependency><br />    </dependencies><br /></dependencyManagement><br /><dependencies><br />    <!-- The following two dependencies are for the <br />         aws-lambda-java-events library. --><br />    <dependency><br />        <groupId>com.amazonaws</groupId><br />        <artifactId>aws-lambda-java-core</artifactId><br />        <version>1.2.3</version>     <br />    </dependency><br />    <dependency><br />        <groupId>com.amazonaws</groupId><br />        <artifactId>aws-lambda-java-events</artifactId><br />        <version>3.15.0</version><br />    </dependency><br />    <!-- Add other SDK dependencies that you need. --><br /></dependencies></pre>  | 