本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
使用AWS SDK for PHP版本 3 向 Amazon CloudWatch 活动发送事件
CloudWatch 事件向任意目标提供近乎实时的系统事件流,这些事件描述了 Amazon Web Services (AWS) 资源的变化。通过简单规则,您可以匹配事件并将事件路由到一个或多个目标函数或流。
以下示例演示如何:
-
使用创建规则PutRule。
-
使用将目标添加到规则中PutTargets。
-
使用向事件发送自定义 CloudWatch 事件PutEvents。
的所有示例代码都可以在此AWS SDK for PHP处找到 GitHub
凭证
运行示例代码之前,请配置您的 AWS 凭证,如 凭证 中所述。然后导入 AWS 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());
}