

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

# 使用 Amazon CloudWatch 活动
<a name="examples-cloudwatch-send-events"></a>

 CloudWatch 事件提供近乎实时的系统事件流，这些事件描述了 Amazon EC2 实例、 Lambda 函数、 Kinesis 流、 Amazon ECS 任务、 Step Functions 状态机、 Amazon SNS 主题、 Amazon SQS 队列或内置目标的 AWS 资源变化。通过使用简单的规则，您可以匹配事件并将事件路由到一个或多个目标函数或流。

Amazon EventBridge 是 CloudWatch 活动的[演变](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-cwe-now-eb.html)。这两项服务使用相同的 API，因此您可以继续使用 SDK 提供的[CloudWatch 事件客户端](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/cloudwatch/CloudWatchClient.html)，也可以迁移到适用于 Java 的 SDK CloudWatch 的事件[EventBridge 客户端](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/eventbridge/EventBridgeClient.html)功能。 CloudWatch 活动[用户指南文档](https://docs.aws.amazon.com/eventbridge/latest/userguide/index.html)和 [API 参考](https://docs.aws.amazon.com/eventbridge/latest/APIReference/index.html)现在可通过 EventBridge 文档网站获得。

## 添加事件
<a name="add-events"></a>

要添加自定义 CloudWatch 事件，请使用包含一个[https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/cloudwatchevents/model/PutEventsRequest.html](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/cloudwatchevents/model/PutEventsRequest.html)或多个提供每个事件详细信息的[https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/cloudwatchevents/model/PutEventsRequestEntry.html](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/cloudwatchevents/model/PutEventsRequestEntry.html)对象来调用该`CloudWatchEventsClient’s``putEvents`方法。您可以为条目指定多个参数，例如事件的来源和类型、与事件相关联的资源等等。

**注意**  
对于每个 `putEvents` 调用，您最多可以指定 10 个事件。

 **导入** 

```
import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;
import software.amazon.awssdk.services.cloudwatchevents.CloudWatchEventsClient;
import software.amazon.awssdk.services.cloudwatchevents.model.PutEventsRequest;
import software.amazon.awssdk.services.cloudwatchevents.model.PutEventsRequestEntry;
```

 **代码** 

```
    public static void putCWEvents(CloudWatchEventsClient cwe, String resourceArn ) {

        try {

            final String EVENT_DETAILS =
                "{ \"key1\": \"value1\", \"key2\": \"value2\" }";

            PutEventsRequestEntry requestEntry = PutEventsRequestEntry.builder()
                    .detail(EVENT_DETAILS)
                    .detailType("sampleSubmitted")
                    .resources(resourceArn)
                    .source("aws-sdk-java-cloudwatch-example")
                    .build();

            PutEventsRequest request = PutEventsRequest.builder()
                    .entries(requestEntry)
                    .build();

            cwe.putEvents(request);
            System.out.println("Successfully put CloudWatch event");

        } catch (CloudWatchException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```

请参阅上的[完整示例](https://github.com/awsdocs/aws-doc-sdk-examples/blob/0b1785e42949ebf959eaa0f0da4dc2a48f92ea25/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutEvents.java) GitHub。

## 添加规则
<a name="add-rules"></a>

要创建或更新规则，请使用[https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/cloudwatchevents/model/PutRuleRequest.html](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/cloudwatchevents/model/PutRuleRequest.html)具有规则名称和可选参数（例如[事件模式](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-event-patterns.html)、要与规则关联的 IAM 角色以及描述规则运行频率的[调度表达式](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-create-rule-schedule.html)）来调用`CloudWatchEventsClient’s``putRule`方法。

 **导入** 

```
import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;
import software.amazon.awssdk.services.cloudwatchevents.CloudWatchEventsClient;
import software.amazon.awssdk.services.cloudwatchevents.model.PutRuleRequest;
import software.amazon.awssdk.services.cloudwatchevents.model.PutRuleResponse;
import software.amazon.awssdk.services.cloudwatchevents.model.RuleState;
```

 **代码** 

```
    public static void putCWRule(CloudWatchEventsClient cwe, String ruleName, String roleArn) {

        try {
            PutRuleRequest request = PutRuleRequest.builder()
                .name(ruleName)
                .roleArn(roleArn)
                .scheduleExpression("rate(5 minutes)")
                .state(RuleState.ENABLED)
                .build();

            PutRuleResponse response = cwe.putRule(request);
            System.out.printf(
                    "Successfully created CloudWatch events rule %s with arn %s",
                    roleArn, response.ruleArn());
        } catch (
            CloudWatchException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```

请参阅上的[完整示例](https://github.com/awsdocs/aws-doc-sdk-examples/blob/0b1785e42949ebf959eaa0f0da4dc2a48f92ea25/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutRule.java) GitHub。

## 添加目标
<a name="add-targets"></a>

目标是触发规则时调用的资源。示例目标包括 Amazon EC2 实例、 Lambda 函数、 Kinesis 流、 Amazon ECS 任务、 Step Functions 状态机和内置目标。

要向规则添加目标，请使用 [https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/cloudwatchevents/model/PutTargetsRequest.html](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/cloudwatchevents/model/PutTargetsRequest.html)（包含要更新的规则和要添加到规则的目标列表）来调用 `CloudWatchEventsClient’s` `putTargets` 方法。

 **导入** 

```
import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;
import software.amazon.awssdk.services.cloudwatchevents.CloudWatchEventsClient;
import software.amazon.awssdk.services.cloudwatchevents.model.PutTargetsRequest;
import software.amazon.awssdk.services.cloudwatchevents.model.PutTargetsResponse;
import software.amazon.awssdk.services.cloudwatchevents.model.Target;
```

 **代码** 

```
    public static void putCWTargets(CloudWatchEventsClient cwe, String ruleName, String functionArn, String targetId ) {

        try {
            Target target = Target.builder()
                .arn(functionArn)
                .id(targetId)
                .build();

            PutTargetsRequest request = PutTargetsRequest.builder()
                .targets(target)
                .rule(ruleName)
                .build();

            PutTargetsResponse response = cwe.putTargets(request);
            System.out.printf(
                "Successfully created CloudWatch events target for rule %s",
                ruleName);
        } catch (CloudWatchException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```

请参阅上的[完整示例](https://github.com/awsdocs/aws-doc-sdk-examples/blob/0b1785e42949ebf959eaa0f0da4dc2a48f92ea25/javav2/example_code/cloudwatch/src/main/java/com/example/cloudwatch/PutTargets.java) GitHub。

## 更多信息
<a name="more-information"></a>
+  在 Amazon EventBridge 用户指南 PutEvents中使用@@ [添加事件](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-putevents.html)
+  在 Amazon EventBridge 用户指南中@@ [安排规则表达式](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-create-rule-schedule.html#eb-create-scheduled-rule-schedule)
+  Amazon EventBridge 用户指南 CloudWatch Events中的@@ [事件类型](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-service-event.html)
+  Amazon EventBridge 用户指南中的@@ [事件模式](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-event-patterns.html)
+  [PutEvents](https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_PutEvents.html)在 Amazon EventBridge API 参考中
+  [PutTargets](https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_PutTargets.html)在 Amazon EventBridge API 参考中
+  [PutRule](https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_PutRule.html)在 Amazon EventBridge API 参考中