PutRule与 S Amazon DK 或命令行工具配合使用 - Amazon EventBridge
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

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

PutRule与 S Amazon DK 或命令行工具配合使用

以下代码示例显示了如何使用PutRule

操作示例是大型程序的代码摘录,必须在上下文中运行。您可以在以下代码示例中查看此操作的上下文:

.NET
Amazon SDK for .NET
注意

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

创建规则,将对象添加到 Amazon Simple Storage Service 桶时触发。

/// <summary> /// Create a new event rule that triggers when an Amazon S3 object is created in a bucket. /// </summary> /// <param name="roleArn">The ARN of the role.</param> /// <param name="ruleName">The name to give the rule.</param> /// <param name="bucketName">The name of the bucket to trigger the event.</param> /// <returns>The ARN of the new rule.</returns> public async Task<string> PutS3UploadRule(string roleArn, string ruleName, string bucketName) { string eventPattern = "{" + "\"source\": [\"aws.s3\"]," + "\"detail-type\": [\"Object Created\"]," + "\"detail\": {" + "\"bucket\": {" + "\"name\": [\"" + bucketName + "\"]" + "}" + "}" + "}"; var response = await _amazonEventBridge.PutRuleAsync( new PutRuleRequest() { Name = ruleName, Description = "Example S3 upload rule for EventBridge", RoleArn = roleArn, EventPattern = eventPattern }); return response.RuleArn; }

创建使用自定义模式的规则。

/// <summary> /// Update a rule to use a custom defined event pattern. /// </summary> /// <param name="ruleName">The name of the rule to update.</param> /// <returns>The ARN of the updated rule.</returns> public async Task<string> UpdateCustomEventPattern(string ruleName) { string customEventsPattern = "{" + "\"source\": [\"ExampleSource\"]," + "\"detail-type\": [\"ExampleType\"]" + "}"; var response = await _amazonEventBridge.PutRuleAsync( new PutRuleRequest() { Name = ruleName, Description = "Custom test rule", EventPattern = customEventsPattern }); return response.RuleArn; }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NET API 参考PutRule中的。

C++
SDK for C++
注意

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

包含所需的文件。

#include <aws/core/Aws.h> #include <aws/events/EventBridgeClient.h> #include <aws/events/model/PutRuleRequest.h> #include <aws/events/model/PutRuleResult.h> #include <aws/core/utils/Outcome.h> #include <iostream>

创建 规则。

Aws::CloudWatchEvents::EventBridgeClient cwe; Aws::CloudWatchEvents::Model::PutRuleRequest request; request.SetName(rule_name); request.SetRoleArn(role_arn); request.SetScheduleExpression("rate(5 minutes)"); request.SetState(Aws::CloudWatchEvents::Model::RuleState::ENABLED); auto outcome = cwe.PutRule(request); if (!outcome.IsSuccess()) { std::cout << "Failed to create CloudWatch events rule " << rule_name << ": " << outcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully created CloudWatch events rule " << rule_name << " with resulting Arn " << outcome.GetResult().GetRuleArn() << std::endl; }
  • 有关 API 的详细信息,请参阅 Amazon SDK for C++ API 参考PutRule中的。

CLI
Amazon CLI

创建 CloudWatch 活动规则

该示例创建一条可在协调世界时每天上午 9:00 触发的规则。如果您使用 put-targets 将 Lambda 函数添加为该规则的目标,则可以在每天的指定时间运行该 Lambda 函数:

aws events put-rule --name "DailyLambdaFunction" --schedule-expression "cron(0 9 * * ? *)"

以下示例创建一条规则,将在区域中的任何 EC2 实例更改状态时触发该规则:

aws events put-rule --name "EC2InstanceStateChanges" --event-pattern "{\"source\":[\"aws.ec2\"],\"detail-type\":[\"EC2 Instance State-change Notification\"]}" --role-arn "arn:aws:iam::123456789012:role/MyRoleForThisRule"

以下示例创建一条规则,将在区域中的任何 EC2 实例停止或终止时触发该规则:

aws events put-rule --name "EC2InstanceStateChangeStopOrTerminate" --event-pattern "{\"source\":[\"aws.ec2\"],\"detail-type\":[\"EC2 Instance State-change Notification\"],\"detail\":{\"state\":[\"stopped\",\"terminated\"]}}" --role-arn "arn:aws:iam::123456789012:role/MyRoleForThisRule"
  • 有关 API 的详细信息,请参阅Amazon CLI 命令参考PutRule中的。

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

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

创建计划规则。

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 的详细信息,请参阅 Amazon SDK for Java 2.x API 参考PutRule中的。

JavaScript
适用于 JavaScript (v3) 的软件开发工具包
注意

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

导入 SDK 和客户端模块,然后调用 API。

import { EventBridgeClient, PutRuleCommand } from "@aws-sdk/client-eventbridge"; export const putRule = async ( ruleName = "some-rule", source = "some-source", ) => { const client = new EventBridgeClient({}); const response = await client.send( new PutRuleCommand({ Name: ruleName, EventPattern: JSON.stringify({ source: [source] }), State: "ENABLED", EventBusName: "default", }), ); console.log("PutRule response:"); console.log(response); // PutRule response: // { // '$metadata': { // httpStatusCode: 200, // requestId: 'd7292ced-1544-421b-842f-596326bc7072', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // RuleArn: 'arn:aws:events:us-east-1:xxxxxxxxxxxx:rule/EventBridgeTestRule-1696280037720' // } return response; };
  • 有关 API 的详细信息,请参阅 Amazon SDK for JavaScript API 参考PutRule中的。

适用于 JavaScript (v2) 的软件开发工具包
注意

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

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create CloudWatchEvents service object var ebevents = new AWS.EventBridge({ apiVersion: "2015-10-07" }); var params = { Name: "DEMO_EVENT", RoleArn: "IAM_ROLE_ARN", ScheduleExpression: "rate(5 minutes)", State: "ENABLED", }; ebevents.putRule(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.RuleArn); } });
  • 有关 API 的详细信息,请参阅 Amazon SDK for JavaScript API 参考PutRule中的。

Kotlin
适用于 Kotlin 的 SDK
注意

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

创建计划规则。

suspend fun createScRule(ruleName: String?, cronExpression: String?) { val ruleRequest = PutRuleRequest { name = ruleName eventBusName = "default" scheduleExpression = cronExpression state = RuleState.Enabled description = "A test rule that runs on a schedule created by the Kotlin API" } EventBridgeClient { region = "us-west-2" }.use { eventBrClient -> val ruleResponse = eventBrClient.putRule(ruleRequest) println("The ARN of the new rule is ${ruleResponse.ruleArn}") } }

创建规则,将对象添加到 Amazon Simple Storage Service 桶时触发。

// Create a new event rule that triggers when an Amazon S3 object is created in a bucket. suspend fun addEventRule(roleArnVal: String?, bucketName: String, eventRuleName: String?) { val pattern = """{ "source": ["aws.s3"], "detail-type": ["Object Created"], "detail": { "bucket": { "name": ["$bucketName"] } } }""" val ruleRequest = PutRuleRequest { description = "Created by using the AWS SDK for Kotlin" name = eventRuleName eventPattern = pattern roleArn = roleArnVal } EventBridgeClient { region = "us-east-1" }.use { eventBrClient -> val ruleResponse = eventBrClient.putRule(ruleRequest) println("The ARN of the new rule is ${ruleResponse.ruleArn}") } }
  • 有关 API 的详细信息,请参阅适用PutRule于 K otlin 的Amazon SDK API 参考

有关 S Amazon DK 开发者指南和代码示例的完整列表,请参阅 EventBridge 与 Amazon SDK 一起使用。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。