使用Amazon SDK for PHP版本 3 向 Amazon CloudWatch 活动发送事件 - Amazon SDK for PHP
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

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

使用Amazon SDK for PHP版本 3 向 Amazon CloudWatch 活动发送事件

CloudWatch 事件向任意目标提供近乎实时的系统事件流,这些事件描述了 Amazon Web Services (Amazon) 资源的变化。通过简单规则,您可以匹配事件并将事件路由到一个或多个目标函数或流。

以下示例演示如何:

  • 使用创建规则PutRule

  • 使用将目标添加到规则中PutTargets

  • 使用向事件发送自定义 CloudWatch 事件PutEvents

的所有示例代码都可以在此Amazon SDK for PHP处找到 GitHub

凭证

运行示例代码之前,请配置您的 Amazon 凭证,如 凭证 中所述。然后导入 Amazon SDK for PHP,如 基本用法 中所述。

创建规则

导入

require 'vendor/autoload.php'; use Aws\Exception\AwsException;

示例代码

$client = new Aws\cloudwatchevents\cloudwatcheventsClient([ 'profile' => 'default', 'region' => 'us-west-2', 'version' => '2015-10-07' ]); try { $result = $client->putRule([ 'Name' => 'DEMO_EVENT', // REQUIRED 'RoleArn' => 'IAM_ROLE_ARN', 'ScheduleExpression' => 'rate(5 minutes)', 'State' => 'ENABLED', ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }

向规则中添加目标

导入

require 'vendor/autoload.php'; use Aws\Exception\AwsException;

示例代码

$client = new Aws\cloudwatchevents\cloudwatcheventsClient([ 'profile' => 'default', 'region' => 'us-west-2', 'version' => '2015-10-07' ]); try { $result = $client->putTargets([ 'Rule' => 'DEMO_EVENT', // REQUIRED 'Targets' => [ // REQUIRED [ 'Arn' => 'LAMBDA_FUNCTION_ARN', // REQUIRED 'Id' => 'myCloudWatchEventsTarget' // REQUIRED ], ], ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }

发送自定义事件

导入

require 'vendor/autoload.php'; use Aws\Exception\AwsException;

示例代码

$client = new Aws\cloudwatchevents\cloudwatcheventsClient([ 'profile' => 'default', 'region' => 'us-west-2', 'version' => '2015-10-07' ]); try { $result = $client->putEvents([ 'Entries' => [ // REQUIRED [ 'Detail' => '<string>', 'DetailType' => '<string>', 'Resources' => ['<string>'], 'Source' => '<string>', 'Time' => time() ], ], ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }