使用 适用于 PHP 的 Amazon SDK 版本 3 来将事件发送到 Amazon CloudWatch Events
CloudWatch Events 提供几乎实时的系统事件流,这些事件描述了 Amazon Web Services (Amazon) 资源中针对任何不同目标的更改。通过简单规则,您可以匹配事件并将事件路由到一个或多个目标函数或流。
以下示例演示如何:
-
使用 PutRule 创建规则。
-
使用 PutTargets 向规则中添加目标。
-
使用 PutEvents 向 CloudWatch Events 发送自定义事件。
适用于 PHP 的 Amazon SDKGitHub 上提供了
凭证
运行示例代码之前,请配置您的 Amazon 凭证,如 通过适用于 PHP 的 Amazon SDK 版本 3 使用 Amazon 进行身份验证 中所述。然后导入 适用于 PHP 的 Amazon SDK,如 安装适用于 PHP 的 Amazon SDK 版本 3 中所述。
创建规则
导入。
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()); }