Word for Java 2.x를 사용한 SDK EventBridge 예제 - AWS SDK 코드 예제

AWS Doc SDK ExamplesWord AWS SDK 리포지토리에는 더 많은 GitHub 예제가 있습니다.

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

Word for Java 2.x를 사용한 SDK EventBridge 예제

다음 코드 예제에서는 AWS SDK for Java 2.x with EventBridge를 사용하여 작업을 수행하고 일반적인 시나리오를 구현하는 방법을 보여줍니다.

기본 사항은 서비스 내에서 필수 작업을 수행하는 방법을 보여주는 코드 예제입니다.

작업은 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 작업은 개별 서비스 함수를 직접적으로 호출하는 방법을 보여주며 관련 시나리오의 컨텍스트에 맞는 작업을 볼 수 있습니다.

시나리오는 동일한 서비스 내에서 또는 다른 AWS 서비스와 결합된 상태에서 여러 함수를 호출하여 특정 태스크를 수행하는 방법을 보여주는 코드 예제입니다.

각 예제에는 컨텍스트에서 코드를 설정하고 실행하는 방법에 대한 지침을 찾을 수 있는 전체 소스 코드에 대한 링크가 포함되어 있습니다.

시작

다음 코드 예제에서는 EventBridge 사용을 시작하는 방법을 보여줍니다.

Java 2.x용 SDK
참고

더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

/** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * */ public class HelloEventBridge { public static void main(String[] args) { Region region = Region.US_WEST_2; EventBridgeClient eventBrClient = EventBridgeClient.builder() .region(region) .build(); listBuses(eventBrClient); eventBrClient.close(); } public static void listBuses(EventBridgeClient eventBrClient) { try { ListEventBusesRequest busesRequest = ListEventBusesRequest.builder() .limit(10) .build(); ListEventBusesResponse response = eventBrClient.listEventBuses(busesRequest); List<EventBus> buses = response.eventBuses(); for (EventBus bus : buses) { System.out.println("The name of the event bus is: " + bus.name()); System.out.println("The ARN of the event bus is: " + bus.arn()); } } catch (EventBridgeException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • API 세부 정보는 ListEventBuses AWS SDK for Java 2.x 참조의 API를 참조하세요.

기본 사항

다음 코드 예시는 다음과 같은 작업을 수행하는 방법을 보여줍니다.

  • 규칙을 만들고 여기에 대상을 추가하세요.

  • 규칙을 활성화 및 비활성화합니다.

  • 규칙과 대상을 나열하고 업데이트합니다.

  • 이벤트를 전송하고 리소스를 정리합니다.

Java 2.x용 SDK
참고

더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

/** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * * This Java code example performs the following tasks: * * This Java V2 example performs the following tasks with Amazon EventBridge: * * 1. Creates an AWS Identity and Access Management (IAM) role to use with * Amazon EventBridge. * 2. Amazon Simple Storage Service (Amazon S3) bucket with EventBridge events * enabled. * 3. Creates a rule that triggers when an object is uploaded to Amazon S3. * 4. Lists rules on the event bus. * 5. Creates a new Amazon Simple Notification Service (Amazon SNS) topic and * lets the user subscribe to it. * 6. Adds a target to the rule that sends an email to the specified topic. * 7. Creates an EventBridge event that sends an email when an Amazon S3 object * is created. * 8. Lists Targets. * 9. Lists the rules for the same target. * 10. Triggers the rule by uploading a file to the Amazon S3 bucket. * 11. Disables a specific rule. * 12. Checks and print the state of the rule. * 13. Adds a transform to the rule to change the text of the email. * 14. Enables a specific rule. * 15. Triggers the updated rule by uploading a file to the Amazon S3 bucket. * 16. Updates the rule to be a custom rule pattern. * 17. Sending an event to trigger the rule. * 18. Cleans up resources. * */ public class EventbridgeMVP { public static final String DASHES = new String(new char[80]).replace("\0", "-"); public static void main(String[] args) throws InterruptedException, IOException { final String usage = """ Usage: <roleName> <bucketName> <topicName> <eventRuleName> Where: roleName - The name of the role to create. bucketName - The Amazon Simple Storage Service (Amazon S3) bucket name to create. topicName - The name of the Amazon Simple Notification Service (Amazon SNS) topic to create. eventRuleName - The Amazon EventBridge rule name to create. """; if (args.length != 5) { System.out.println(usage); System.exit(1); } String polJSON = "{" + "\"Version\": \"2012-10-17\"," + "\"Statement\": [{" + "\"Effect\": \"Allow\"," + "\"Principal\": {" + "\"Service\": \"events.amazonaws.com\"" + "}," + "\"Action\": \"sts:AssumeRole\"" + "}]" + "}"; Scanner sc = new Scanner(System.in); String roleName = args[0]; String bucketName = args[1]; String topicName = args[2]; String eventRuleName = args[3]; Region region = Region.US_EAST_1; EventBridgeClient eventBrClient = EventBridgeClient.builder() .region(region) .build(); S3Client s3Client = S3Client.builder() .region(region) .build(); Region regionGl = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() .region(regionGl) .build(); SnsClient snsClient = SnsClient.builder() .region(region) .build(); System.out.println(DASHES); System.out.println("Welcome to the Amazon EventBridge example scenario."); System.out.println(DASHES); System.out.println(DASHES); System.out .println("1. Create an AWS Identity and Access Management (IAM) role to use with Amazon EventBridge."); String roleArn = createIAMRole(iam, roleName, polJSON); System.out.println(DASHES); System.out.println(DASHES); System.out.println("2. Create an S3 bucket with EventBridge events enabled."); if (checkBucket(s3Client, bucketName)) { System.out.println("Bucket " + bucketName + " already exists. Ending this scenario."); System.exit(1); } createBucket(s3Client, bucketName); Thread.sleep(3000); setBucketNotification(s3Client, bucketName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("3. Create a rule that triggers when an object is uploaded to Amazon S3."); Thread.sleep(10000); addEventRule(eventBrClient, roleArn, bucketName, eventRuleName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("4. List rules on the event bus."); listRules(eventBrClient); System.out.println(DASHES); System.out.println(DASHES); System.out.println("5. Create a new SNS topic for testing and let the user subscribe to the topic."); String topicArn = createSnsTopic(snsClient, topicName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("6. Add a target to the rule that sends an email to the specified topic."); System.out.println("Enter your email to subscribe to the Amazon SNS topic:"); String email = sc.nextLine(); subEmail(snsClient, topicArn, email); System.out.println( "Use the link in the email you received to confirm your subscription. Then, press Enter to continue."); sc.nextLine(); System.out.println(DASHES); System.out.println(DASHES); System.out.println("7. Create an EventBridge event that sends an email when an Amazon S3 object is created."); addSnsEventRule(eventBrClient, eventRuleName, topicArn, topicName, eventRuleName, bucketName); System.out.println(DASHES); System.out.println(DASHES); System.out.println(" 8. List Targets."); listTargets(eventBrClient, eventRuleName); System.out.println(DASHES); System.out.println(DASHES); System.out.println(" 9. List the rules for the same target."); listTargetRules(eventBrClient, topicArn); System.out.println(DASHES); System.out.println(DASHES); System.out.println(" 10. Trigger the rule by uploading a file to the S3 bucket."); System.out.println("Press Enter to continue."); sc.nextLine(); uploadTextFiletoS3(s3Client, bucketName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("11. Disable a specific rule."); changeRuleState(eventBrClient, eventRuleName, false); System.out.println(DASHES); System.out.println(DASHES); System.out.println("12. Check and print the state of the rule."); checkRule(eventBrClient, eventRuleName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("13. Add a transform to the rule to change the text of the email."); updateSnsEventRule(eventBrClient, topicArn, eventRuleName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("14. Enable a specific rule."); changeRuleState(eventBrClient, eventRuleName, true); System.out.println(DASHES); System.out.println(DASHES); System.out.println(" 15. Trigger the updated rule by uploading a file to the S3 bucket."); System.out.println("Press Enter to continue."); sc.nextLine(); uploadTextFiletoS3(s3Client, bucketName); System.out.println(DASHES); System.out.println(DASHES); System.out.println(" 16. Update the rule to be a custom rule pattern."); updateToCustomRule(eventBrClient, eventRuleName); System.out.println("Updated event rule " + eventRuleName + " to use a custom pattern."); updateCustomRuleTargetWithTransform(eventBrClient, topicArn, eventRuleName); System.out.println("Updated event target " + topicArn + "."); System.out.println(DASHES); System.out.println(DASHES); System.out.println("17. Sending an event to trigger the rule. This will trigger a subscription email."); triggerCustomRule(eventBrClient, email); System.out.println("Events have been sent. Press Enter to continue."); sc.nextLine(); System.out.println(DASHES); System.out.println(DASHES); System.out.println("18. Clean up resources."); System.out.println("Do you want to clean up resources (y/n)"); String ans = sc.nextLine(); if (ans.compareTo("y") == 0) { cleanupResources(eventBrClient, snsClient, s3Client, iam, topicArn, eventRuleName, bucketName, roleName); } else { System.out.println("The resources will not be cleaned up. "); } System.out.println(DASHES); System.out.println(DASHES); System.out.println("The Amazon EventBridge example scenario has successfully completed."); System.out.println(DASHES); } public static void cleanupResources(EventBridgeClient eventBrClient, SnsClient snsClient, S3Client s3Client, IamClient iam, String topicArn, String eventRuleName, String bucketName, String roleName) { System.out.println("Removing all targets from the event rule."); deleteTargetsFromRule(eventBrClient, eventRuleName); deleteRuleByName(eventBrClient, eventRuleName); deleteSNSTopic(snsClient, topicArn); deleteS3Bucket(s3Client, bucketName); deleteRole(iam, roleName); } public static void deleteRole(IamClient iam, String roleName) { String policyArn = "arn:aws:iam::aws:policy/AmazonEventBridgeFullAccess"; DetachRolePolicyRequest policyRequest = DetachRolePolicyRequest.builder() .policyArn(policyArn) .roleName(roleName) .build(); iam.detachRolePolicy(policyRequest); System.out.println("Successfully detached policy " + policyArn + " from role " + roleName); // Delete the role. DeleteRoleRequest roleRequest = DeleteRoleRequest.builder() .roleName(roleName) .build(); iam.deleteRole(roleRequest); System.out.println("*** Successfully deleted " + roleName); } public static void deleteS3Bucket(S3Client s3Client, String bucketName) { // Remove all the objects from the S3 bucket. ListObjectsRequest listObjects = ListObjectsRequest.builder() .bucket(bucketName) .build(); ListObjectsResponse res = s3Client.listObjects(listObjects); List<S3Object> objects = res.contents(); ArrayList<ObjectIdentifier> toDelete = new ArrayList<>(); for (S3Object myValue : objects) { toDelete.add(ObjectIdentifier.builder() .key(myValue.key()) .build()); } DeleteObjectsRequest dor = DeleteObjectsRequest.builder() .bucket(bucketName) .delete(Delete.builder() .objects(toDelete).build()) .build(); s3Client.deleteObjects(dor); // Delete the S3 bucket. DeleteBucketRequest deleteBucketRequest = DeleteBucketRequest.builder() .bucket(bucketName) .build(); s3Client.deleteBucket(deleteBucketRequest); System.out.println("You have deleted the bucket and the objects"); } // Delete the SNS topic. public static void deleteSNSTopic(SnsClient snsClient, String topicArn) { try { DeleteTopicRequest request = DeleteTopicRequest.builder() .topicArn(topicArn) .build(); DeleteTopicResponse result = snsClient.deleteTopic(request); System.out.println("\n\nStatus was " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void deleteRuleByName(EventBridgeClient eventBrClient, String ruleName) { DeleteRuleRequest ruleRequest = DeleteRuleRequest.builder() .name(ruleName) .build(); eventBrClient.deleteRule(ruleRequest); System.out.println("Successfully deleted the rule"); } public static void deleteTargetsFromRule(EventBridgeClient eventBrClient, String eventRuleName) { // First, get all targets that will be deleted. ListTargetsByRuleRequest request = ListTargetsByRuleRequest.builder() .rule(eventRuleName) .build(); ListTargetsByRuleResponse response = eventBrClient.listTargetsByRule(request); List<Target> allTargets = response.targets(); // Get all targets and delete them. for (Target myTarget : allTargets) { RemoveTargetsRequest removeTargetsRequest = RemoveTargetsRequest.builder() .rule(eventRuleName) .ids(myTarget.id()) .build(); eventBrClient.removeTargets(removeTargetsRequest); System.out.println("Successfully removed the target"); } } public static void triggerCustomRule(EventBridgeClient eventBrClient, String email) { String json = "{" + "\"UserEmail\": \"" + email + "\"," + "\"Message\": \"This event was generated by example code.\"," + "\"UtcTime\": \"Now.\"" + "}"; PutEventsRequestEntry entry = PutEventsRequestEntry.builder() .source("ExampleSource") .detail(json) .detailType("ExampleType") .build(); PutEventsRequest eventsRequest = PutEventsRequest.builder() .entries(entry) .build(); eventBrClient.putEvents(eventsRequest); } public static void updateCustomRuleTargetWithTransform(EventBridgeClient eventBrClient, String topicArn, String ruleName) { String targetId = java.util.UUID.randomUUID().toString(); InputTransformer inputTransformer = InputTransformer.builder() .inputTemplate("\"Notification: sample event was received.\"") .build(); Target target = Target.builder() .id(targetId) .arn(topicArn) .inputTransformer(inputTransformer) .build(); try { PutTargetsRequest targetsRequest = PutTargetsRequest.builder() .rule(ruleName) .targets(target) .eventBusName(null) .build(); eventBrClient.putTargets(targetsRequest); } catch (EventBridgeException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void updateToCustomRule(EventBridgeClient eventBrClient, String ruleName) { String customEventsPattern = "{" + "\"source\": [\"ExampleSource\"]," + "\"detail-type\": [\"ExampleType\"]" + "}"; PutRuleRequest request = PutRuleRequest.builder() .name(ruleName) .description("Custom test rule") .eventPattern(customEventsPattern) .build(); eventBrClient.putRule(request); } // Update an Amazon S3 object created rule with a transform on the target. public static void updateSnsEventRule(EventBridgeClient eventBrClient, String topicArn, String ruleName) { String targetId = java.util.UUID.randomUUID().toString(); Map<String, String> myMap = new HashMap<>(); myMap.put("bucket", "$.detail.bucket.name"); myMap.put("time", "$.time"); InputTransformer inputTransformer = InputTransformer.builder() .inputTemplate("\"Notification: an object was uploaded to bucket <bucket> at <time>.\"") .inputPathsMap(myMap) .build(); Target target = Target.builder() .id(targetId) .arn(topicArn) .inputTransformer(inputTransformer) .build(); try { PutTargetsRequest targetsRequest = PutTargetsRequest.builder() .rule(ruleName) .targets(target) .eventBusName(null) .build(); eventBrClient.putTargets(targetsRequest); } catch (EventBridgeException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void checkRule(EventBridgeClient eventBrClient, String eventRuleName) { try { DescribeRuleRequest ruleRequest = DescribeRuleRequest.builder() .name(eventRuleName) .build(); DescribeRuleResponse response = eventBrClient.describeRule(ruleRequest); System.out.println("The state of the rule is " + response.stateAsString()); } catch (EventBridgeException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void changeRuleState(EventBridgeClient eventBrClient, String eventRuleName, Boolean isEnabled) { try { if (!isEnabled) { System.out.println("Disabling the rule: " + eventRuleName); DisableRuleRequest ruleRequest = DisableRuleRequest.builder() .name(eventRuleName) .build(); eventBrClient.disableRule(ruleRequest); } else { System.out.println("Enabling the rule: " + eventRuleName); EnableRuleRequest ruleRequest = EnableRuleRequest.builder() .name(eventRuleName) .build(); eventBrClient.enableRule(ruleRequest); } } catch (EventBridgeException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } // Create and upload a file to an S3 bucket to trigger an event. public static void uploadTextFiletoS3(S3Client s3Client, String bucketName) throws IOException { // Create a unique file name. String fileSuffix = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); String fileName = "TextFile" + fileSuffix + ".txt"; File myFile = new File(fileName); FileWriter fw = new FileWriter(myFile.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write("This is a sample file for testing uploads."); bw.close(); try { PutObjectRequest putOb = PutObjectRequest.builder() .bucket(bucketName) .key(fileName) .build(); s3Client.putObject(putOb, RequestBody.fromFile(myFile)); } catch (S3Exception e) { System.err.println(e.getMessage()); System.exit(1); } } public static void listTargetRules(EventBridgeClient eventBrClient, String topicArn) { ListRuleNamesByTargetRequest ruleNamesByTargetRequest = ListRuleNamesByTargetRequest.builder() .targetArn(topicArn) .build(); ListRuleNamesByTargetResponse response = eventBrClient.listRuleNamesByTarget(ruleNamesByTargetRequest); List<String> rules = response.ruleNames(); for (String rule : rules) { System.out.println("The rule name is " + rule); } } public static void listTargets(EventBridgeClient eventBrClient, String ruleName) { ListTargetsByRuleRequest ruleRequest = ListTargetsByRuleRequest.builder() .rule(ruleName) .build(); ListTargetsByRuleResponse res = eventBrClient.listTargetsByRule(ruleRequest); List<Target> targetsList = res.targets(); for (Target target: targetsList) { System.out.println("Target ARN: "+target.arn()); } } // Add a rule which triggers an SNS target when a file is uploaded to an S3 // bucket. public static void addSnsEventRule(EventBridgeClient eventBrClient, String ruleName, String topicArn, String topicName, String eventRuleName, String bucketName) { String targetID = java.util.UUID.randomUUID().toString(); Target myTarget = Target.builder() .id(targetID) .arn(topicArn) .build(); List<Target> targets = new ArrayList<>(); targets.add(myTarget); PutTargetsRequest request = PutTargetsRequest.builder() .eventBusName(null) .targets(targets) .rule(ruleName) .build(); eventBrClient.putTargets(request); System.out.println("Added event rule " + eventRuleName + " with Amazon SNS target " + topicName + " for bucket " + bucketName + "."); } public static void subEmail(SnsClient snsClient, String topicArn, String email) { try { SubscribeRequest request = SubscribeRequest.builder() .protocol("email") .endpoint(email) .returnSubscriptionArn(true) .topicArn(topicArn) .build(); SubscribeResponse result = snsClient.subscribe(request); System.out.println("Subscription ARN: " + result.subscriptionArn() + "\n\n Status is " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void listRules(EventBridgeClient eventBrClient) { try { ListRulesRequest rulesRequest = ListRulesRequest.builder() .eventBusName("default") .limit(10) .build(); ListRulesResponse response = eventBrClient.listRules(rulesRequest); List<Rule> rules = response.rules(); for (Rule rule : rules) { System.out.println("The rule name is : " + rule.name()); System.out.println("The rule description is : " + rule.description()); System.out.println("The rule state is : " + rule.stateAsString()); } } catch (EventBridgeException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static String createSnsTopic(SnsClient snsClient, String topicName) { String topicPolicy = "{" + "\"Version\": \"2012-10-17\"," + "\"Statement\": [{" + "\"Sid\": \"EventBridgePublishTopic\"," + "\"Effect\": \"Allow\"," + "\"Principal\": {" + "\"Service\": \"events.amazonaws.com\"" + "}," + "\"Resource\": \"*\"," + "\"Action\": \"sns:Publish\"" + "}]" + "}"; Map<String, String> topicAttributes = new HashMap<>(); topicAttributes.put("Policy", topicPolicy); CreateTopicRequest topicRequest = CreateTopicRequest.builder() .name(topicName) .attributes(topicAttributes) .build(); CreateTopicResponse response = snsClient.createTopic(topicRequest); System.out.println("Added topic " + topicName + " for email subscriptions."); return response.topicArn(); } // Create a new event rule that triggers when an Amazon S3 object is created in // a bucket. public static void addEventRule(EventBridgeClient eventBrClient, String roleArn, String bucketName, String eventRuleName) { String pattern = "{\n" + " \"source\": [\"aws.s3\"],\n" + " \"detail-type\": [\"Object Created\"],\n" + " \"detail\": {\n" + " \"bucket\": {\n" + " \"name\": [\"" + bucketName + "\"]\n" + " }\n" + " }\n" + "}"; try { PutRuleRequest ruleRequest = PutRuleRequest.builder() .description("Created by using the AWS SDK for Java v2") .name(eventRuleName) .eventPattern(pattern) .roleArn(roleArn) .build(); PutRuleResponse ruleResponse = eventBrClient.putRule(ruleRequest); System.out.println("The ARN of the new rule is " + ruleResponse.ruleArn()); } catch (EventBridgeException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } // Determine if the S3 bucket exists. public static Boolean checkBucket(S3Client s3Client, String bucketName) { try { HeadBucketRequest headBucketRequest = HeadBucketRequest.builder() .bucket(bucketName) .build(); s3Client.headBucket(headBucketRequest); return true; } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); } return false; } // Set the S3 bucket notification configuration. public static void setBucketNotification(S3Client s3Client, String bucketName) { try { EventBridgeConfiguration eventBridgeConfiguration = EventBridgeConfiguration.builder() .build(); NotificationConfiguration configuration = NotificationConfiguration.builder() .eventBridgeConfiguration(eventBridgeConfiguration) .build(); PutBucketNotificationConfigurationRequest configurationRequest = PutBucketNotificationConfigurationRequest .builder() .bucket(bucketName) .notificationConfiguration(configuration) .skipDestinationValidation(true) .build(); s3Client.putBucketNotificationConfiguration(configurationRequest); System.out.println("Added bucket " + bucketName + " with EventBridge events enabled."); } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void createBucket(S3Client s3Client, String bucketName) { try { S3Waiter s3Waiter = s3Client.waiter(); CreateBucketRequest bucketRequest = CreateBucketRequest.builder() .bucket(bucketName) .build(); s3Client.createBucket(bucketRequest); HeadBucketRequest bucketRequestWait = HeadBucketRequest.builder() .bucket(bucketName) .build(); // Wait until the bucket is created and print out the response. WaiterResponse<HeadBucketResponse> waiterResponse = s3Waiter.waitUntilBucketExists(bucketRequestWait); waiterResponse.matched().response().ifPresent(System.out::println); System.out.println(bucketName + " is ready"); } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static String createIAMRole(IamClient iam, String rolename, String polJSON) { try { CreateRoleRequest request = CreateRoleRequest.builder() .roleName(rolename) .assumeRolePolicyDocument(polJSON) .description("Created using the AWS SDK for Java") .build(); CreateRoleResponse response = iam.createRole(request); AttachRolePolicyRequest rolePolicyRequest = AttachRolePolicyRequest.builder() .roleName(rolename) .policyArn("arn:aws:iam::aws:policy/AmazonEventBridgeFullAccess") .build(); iam.attachRolePolicy(rolePolicyRequest); return response.role().arn(); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } }

작업

다음 코드 예시에서는 DeleteRule을 사용하는 방법을 보여 줍니다.

Java 2.x용 SDK
참고

더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

public static void deleteRuleByName(EventBridgeClient eventBrClient, String ruleName) { DeleteRuleRequest ruleRequest = DeleteRuleRequest.builder() .name(ruleName) .build(); eventBrClient.deleteRule(ruleRequest); System.out.println("Successfully deleted the rule"); }
  • API 세부 정보는 DeleteRule AWS SDK for Java 2.x 참조의 API를 참조하세요.

다음 코드 예시에서는 DescribeRule을 사용하는 방법을 보여 줍니다.

Java 2.x용 SDK
참고

더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

public static void checkRule(EventBridgeClient eventBrClient, String eventRuleName) { try { DescribeRuleRequest ruleRequest = DescribeRuleRequest.builder() .name(eventRuleName) .build(); DescribeRuleResponse response = eventBrClient.describeRule(ruleRequest); System.out.println("The state of the rule is " + response.stateAsString()); } catch (EventBridgeException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • API 세부 정보는 DescribeRule AWS SDK for Java 2.x 참조의 API를 참조하세요.

다음 코드 예시에서는 DisableRule을 사용하는 방법을 보여 줍니다.

Java 2.x용 SDK
참고

더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

규칙 이름을 사용하여 규칙을 비활성화합니다.

public static void changeRuleState(EventBridgeClient eventBrClient, String eventRuleName, Boolean isEnabled) { try { if (!isEnabled) { System.out.println("Disabling the rule: " + eventRuleName); DisableRuleRequest ruleRequest = DisableRuleRequest.builder() .name(eventRuleName) .build(); eventBrClient.disableRule(ruleRequest); } else { System.out.println("Enabling the rule: " + eventRuleName); EnableRuleRequest ruleRequest = EnableRuleRequest.builder() .name(eventRuleName) .build(); eventBrClient.enableRule(ruleRequest); } } catch (EventBridgeException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • API 세부 정보는 DisableRule AWS SDK for Java 2.x 참조의 API를 참조하세요.

다음 코드 예시에서는 EnableRule을 사용하는 방법을 보여 줍니다.

Java 2.x용 SDK
참고

더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

규칙 이름을 사용하여 규칙을 활성화합니다.

public static void changeRuleState(EventBridgeClient eventBrClient, String eventRuleName, Boolean isEnabled) { try { if (!isEnabled) { System.out.println("Disabling the rule: " + eventRuleName); DisableRuleRequest ruleRequest = DisableRuleRequest.builder() .name(eventRuleName) .build(); eventBrClient.disableRule(ruleRequest); } else { System.out.println("Enabling the rule: " + eventRuleName); EnableRuleRequest ruleRequest = EnableRuleRequest.builder() .name(eventRuleName) .build(); eventBrClient.enableRule(ruleRequest); } } catch (EventBridgeException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • API 세부 정보는 EnableRule AWS SDK for Java 2.x 참조의 API를 참조하세요.

다음 코드 예시에서는 ListRuleNamesByTarget을 사용하는 방법을 보여 줍니다.

Java 2.x용 SDK
참고

더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

대상을 사용하여 모든 규칙 이름을 나열하세요.

public static void listTargetRules(EventBridgeClient eventBrClient, String topicArn) { ListRuleNamesByTargetRequest ruleNamesByTargetRequest = ListRuleNamesByTargetRequest.builder() .targetArn(topicArn) .build(); ListRuleNamesByTargetResponse response = eventBrClient.listRuleNamesByTarget(ruleNamesByTargetRequest); List<String> rules = response.ruleNames(); for (String rule : rules) { System.out.println("The rule name is " + rule); } }

다음 코드 예시에서는 ListRules을 사용하는 방법을 보여 줍니다.

Java 2.x용 SDK
참고

더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

규칙 이름을 사용하여 규칙을 활성화합니다.

public static void listRules(EventBridgeClient eventBrClient) { try { ListRulesRequest rulesRequest = ListRulesRequest.builder() .eventBusName("default") .limit(10) .build(); ListRulesResponse response = eventBrClient.listRules(rulesRequest); List<Rule> rules = response.rules(); for (Rule rule : rules) { System.out.println("The rule name is : " + rule.name()); System.out.println("The rule description is : " + rule.description()); System.out.println("The rule state is : " + rule.stateAsString()); } } catch (EventBridgeException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • API 세부 정보는 ListRules AWS SDK for Java 2.x 참조의 API를 참조하세요.

다음 코드 예시에서는 ListTargetsByRule을 사용하는 방법을 보여 줍니다.

Java 2.x용 SDK
참고

더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

규칙 이름을 사용하여 규칙의 모든 대상을 나열하세요.

public static void listTargets(EventBridgeClient eventBrClient, String ruleName) { ListTargetsByRuleRequest ruleRequest = ListTargetsByRuleRequest.builder() .rule(ruleName) .build(); ListTargetsByRuleResponse res = eventBrClient.listTargetsByRule(ruleRequest); List<Target> targetsList = res.targets(); for (Target target: targetsList) { System.out.println("Target ARN: "+target.arn()); } }
  • API 세부 정보는 ListTargetsByRule AWS SDK for Java 2.x 참조의 API를 참조하세요.

다음 코드 예시에서는 PutEvents을 사용하는 방법을 보여 줍니다.

Java 2.x용 SDK
참고

더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

public static void triggerCustomRule(EventBridgeClient eventBrClient, String email) { String json = "{" + "\"UserEmail\": \"" + email + "\"," + "\"Message\": \"This event was generated by example code.\"," + "\"UtcTime\": \"Now.\"" + "}"; PutEventsRequestEntry entry = PutEventsRequestEntry.builder() .source("ExampleSource") .detail(json) .detailType("ExampleType") .build(); PutEventsRequest eventsRequest = PutEventsRequest.builder() .entries(entry) .build(); eventBrClient.putEvents(eventsRequest); }
  • API 세부 정보는 PutEvents AWS SDK for Java 2.x 참조의 API를 참조하세요.

다음 코드 예시에서는 PutRule을 사용하는 방법을 보여 줍니다.

Java 2.x용 SDK
참고

더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

예약된 규칙을 생성합니다.

public static void createEBRule(EventBridgeClient eventBrClient, String ruleName, String cronExpression) { try { PutRuleRequest ruleRequest = PutRuleRequest.builder() .name(ruleName) .eventBusName("default") .scheduleExpression(cronExpression) .state("ENABLED") .description("A test rule that runs on a schedule created by the Java API") .build(); PutRuleResponse ruleResponse = eventBrClient.putRule(ruleRequest); System.out.println("The ARN of the new rule is " + ruleResponse.ruleArn()); } catch (EventBridgeException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }

객체가 Amazon Simple Storage Service 버킷에 추가될 때 트리거되는 규칙을 생성하세요.

// Create a new event rule that triggers when an Amazon S3 object is created in // a bucket. public static void addEventRule(EventBridgeClient eventBrClient, String roleArn, String bucketName, String eventRuleName) { String pattern = "{\n" + " \"source\": [\"aws.s3\"],\n" + " \"detail-type\": [\"Object Created\"],\n" + " \"detail\": {\n" + " \"bucket\": {\n" + " \"name\": [\"" + bucketName + "\"]\n" + " }\n" + " }\n" + "}"; try { PutRuleRequest ruleRequest = PutRuleRequest.builder() .description("Created by using the AWS SDK for Java v2") .name(eventRuleName) .eventPattern(pattern) .roleArn(roleArn) .build(); PutRuleResponse ruleResponse = eventBrClient.putRule(ruleRequest); System.out.println("The ARN of the new rule is " + ruleResponse.ruleArn()); } catch (EventBridgeException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • API 세부 정보는 PutRule AWS SDK for Java 2.x 참조의 API를 참조하세요.

다음 코드 예시에서는 PutTargets을 사용하는 방법을 보여 줍니다.

Java 2.x용 SDK
참고

더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

Amazon SNS 주제를 규칙의 대상으로 추가합니다.

// Add a rule which triggers an SNS target when a file is uploaded to an S3 // bucket. public static void addSnsEventRule(EventBridgeClient eventBrClient, String ruleName, String topicArn, String topicName, String eventRuleName, String bucketName) { String targetID = java.util.UUID.randomUUID().toString(); Target myTarget = Target.builder() .id(targetID) .arn(topicArn) .build(); List<Target> targets = new ArrayList<>(); targets.add(myTarget); PutTargetsRequest request = PutTargetsRequest.builder() .eventBusName(null) .targets(targets) .rule(ruleName) .build(); eventBrClient.putTargets(request); System.out.println("Added event rule " + eventRuleName + " with Amazon SNS target " + topicName + " for bucket " + bucketName + "."); }

규칙의 대상에 입력 변환기를 추가합니다.

public static void updateCustomRuleTargetWithTransform(EventBridgeClient eventBrClient, String topicArn, String ruleName) { String targetId = java.util.UUID.randomUUID().toString(); InputTransformer inputTransformer = InputTransformer.builder() .inputTemplate("\"Notification: sample event was received.\"") .build(); Target target = Target.builder() .id(targetId) .arn(topicArn) .inputTransformer(inputTransformer) .build(); try { PutTargetsRequest targetsRequest = PutTargetsRequest.builder() .rule(ruleName) .targets(target) .eventBusName(null) .build(); eventBrClient.putTargets(targetsRequest); } catch (EventBridgeException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • API 세부 정보는 PutTargets AWS SDK for Java 2.x 참조의 API를 참조하세요.

다음 코드 예시에서는 RemoveTargets을 사용하는 방법을 보여 줍니다.

Java 2.x용 SDK
참고

더 많은 on GitHub가 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

규칙 이름을 사용하여 규칙의 모든 대상을 제거합니다.

public static void deleteTargetsFromRule(EventBridgeClient eventBrClient, String eventRuleName) { // First, get all targets that will be deleted. ListTargetsByRuleRequest request = ListTargetsByRuleRequest.builder() .rule(eventRuleName) .build(); ListTargetsByRuleResponse response = eventBrClient.listTargetsByRule(request); List<Target> allTargets = response.targets(); // Get all targets and delete them. for (Target myTarget : allTargets) { RemoveTargetsRequest removeTargetsRequest = RemoveTargetsRequest.builder() .rule(eventRuleName) .ids(myTarget.id()) .build(); eventBrClient.removeTargets(removeTargetsRequest); System.out.println("Successfully removed the target"); } }
  • API 세부 정보는 RemoveTargets AWS SDK for Java 2.x 참조의 API를 참조하세요.

시나리오

다음 코드 예제는 버킷이 S3 이벤트 알림을 EventBridge 로 보내고 알림을 Amazon SNS 주제 및 Amazon SQS 대기열로 라우팅하도록 활성화하는 방법을 보여줍니다.

Java 2.x용 SDK
참고

더 많은 on 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; }

다음 코드 예제는 Amazon EventBridge 예약 이벤트에서 호출된 AWS Lambda 함수를 생성하는 방법을 보여줍니다.

Java 2.x용 SDK

AWS Lambda 함수를 호출하는 Amazon EventBridge 예약 이벤트를 생성하는 방법을 보여줍니다. Configure EventBridge 는 cron 표현식을 사용하여 Lambda 함수가 호출되는 시간을 예약합니다. 이 예제에서는 Lambda Java 런타임 API를 사용하여 Lambda 함수를 생성합니다. 이 예제에서는 특정 사용 사례를 수행하기 위해 다양한 AWS 서비스를 호출합니다. 이 예제에서는 1주년 기념일에 직원에게 축하하는 모바일 문자 메시지를 전송하는 앱을 생성하는 방법을 보여줍니다.

전체 소스 코드와 설정 및 실행 방법에 대한 지침은 GitHub의 전체 예제를 참조하세요.

이 예제에서 사용되는 서비스
  • DynamoDB

  • EventBridge

  • Lambda

  • Amazon SNS