View a markdown version of this page

EventBridge 使用向亚马逊发送 S3 事件通知 AWS SDK - AWS SDK 代码示例

D AWS oc AWS SDK 示例 GitHub 存储库中有更多 SDK 示例。

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

EventBridge 使用向亚马逊发送 S3 事件通知 AWS SDK

以下代码示例演示如何允许存储桶向 Amazon SNS 主题和 Amazon SQS 队列发送 S3 事件通知, EventBridge 以及如何将通知路由到 Amazon SNS 主题和 Amazon SQS 队列。

Java
适用于 Java 的 SDK 2.x
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库 中查找完整示例,了解如何进行设置和运行。

/** This method configures a bucket to send events to AWS EventBridge and creates a rule * to route the S3 object created events to a topic and a queue. * * @param bucketName Name of existing bucket * @param topicArn ARN of existing topic to receive S3 event notifications * @param queueArn ARN of existing queue to receive S3 event notifications * * An AWS CloudFormation stack sets up the bucket, queue, topic before the method runs. */ public static String setBucketNotificationToEventBridge(String bucketName, String topicArn, String queueArn) { try { // Enable bucket to emit S3 Event notifications to EventBridge. s3Client.putBucketNotificationConfiguration(b -> b .bucket(bucketName) .notificationConfiguration(b1 -> b1 .eventBridgeConfiguration( SdkBuilder::build) ).build()).join(); // 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; }