AWS Elastic Beanstalk
开发人员指南
AWS 文档中描述的 AWS 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 AWS 服务入门

示例:DynamoDB、CloudWatch 和 SNS

此配置文件会使用适用于 PHP 的 AWS 开发工具包将 DynamoDB 表设置为基于 PHP 的应用程序的会话处理程序。要使用此示例,您必须拥有 IAM 实例配置文件,该文件会添加到环境中的实例,并用来访问 DynamoDB 表。

您可以在 DynamoDB 会话支持示例下载该示例,我们在本步骤会用到这个示例。此示例包含以下文件:

  • 示例应用程序 index.php

  • 配置文件 dynamodb.config,用于创建和配置 DynamoDB 表及其他 AWS 资源,以及在 Elastic Beanstalk 环境中托管该应用程序的 EC2 实例上安装软件

  • 配置文件 options.config,该文件会使用此特定安装的特定设置覆盖 dynamodb.config 中的默认设置

index.php

<?php // Include the SDK using the Composer autoloader require '../vendor/autoload.php'; use Aws\DynamoDb\DynamoDbClient; // Grab the session table name and region from the configuration file list($tableName, $region) = file(__DIR__ . '/../sessiontable'); $tableName = rtrim($tableName); $region = rtrim($region); // Create a DynamoDB client and register the table as the session handler $dynamodb = DynamoDbClient::factory(array('region' => $region)); $handler = $dynamodb->registerSessionHandler(array('table_name' => $tableName, 'hash_key' => 'username')); // Grab the instance ID so we can display the EC2 instance that services the request $instanceId = file_get_contents("http://169.254.169.254/latest/meta-data/instance-id"); ?> <h1>Elastic Beanstalk PHP Sessions Sample</h1> <p>This sample application shows the integration of the Elastic Beanstalk PHP container and the session support for DynamoDB from the AWS SDK for PHP 2. Using DynamoDB session support, the application can be scaled out across multiple web servers. For more details, see the <a href="http://www.amazonaws.cn/php/">PHP Developer Center</a>.</p> <form id="SimpleForm" name="SimpleForm" method="post" action="index.php"> <?php echo 'Request serviced from instance ' . $instanceId . '<br/>'; echo '<br/>'; if (isset($_POST['continue'])) { session_start(); $_SESSION['visits'] = $_SESSION['visits'] + 1; echo 'Welcome back ' . $_SESSION['username'] . '<br/>'; echo 'This is visit number ' . $_SESSION['visits'] . '<br/>'; session_write_close(); echo '<br/>'; echo '<input type="Submit" value="Refresh" name="continue" id="continue"/>'; echo '<input type="Submit" value="Delete Session" name="killsession" id="killsession"/>'; } elseif (isset($_POST['killsession'])) { session_start(); echo 'Goodbye ' . $_SESSION['username'] . '<br/>'; session_destroy(); echo 'Username: <input type="text" name="username" id="username" size="30"/><br/>'; echo '<br/>'; echo '<input type="Submit" value="New Session" name="newsession" id="newsession"/>'; } elseif (isset($_POST['newsession'])) { session_start(); $_SESSION['username'] = $_POST['username']; $_SESSION['visits'] = 1; echo 'Welcome to a new session ' . $_SESSION['username'] . '<br/>'; session_write_close(); echo '<br/>'; echo '<input type="Submit" value="Refresh" name="continue" id="continue"/>'; echo '<input type="Submit" value="Delete Session" name="killsession" id="killsession"/>'; } else { echo 'To get started, enter a username.<br/>'; echo '<br/>'; echo 'Username: <input type="text" name="username" id="username" size="30"/><br/>'; echo '<input type="Submit" value="New Session" name="newsession" id="newsession"/>'; } ?> </form>

.ebextensions/dynamodb.config

Resources: SessionTable: Type: AWS::DynamoDB::Table Properties: KeySchema: HashKeyElement: AttributeName: Fn::GetOptionSetting: OptionName : SessionHashKeyName DefaultValue: "username" AttributeType: Fn::GetOptionSetting: OptionName : SessionHashKeyType DefaultValue: "S" ProvisionedThroughput: ReadCapacityUnits: Fn::GetOptionSetting: OptionName : SessionReadCapacityUnits DefaultValue: 1 WriteCapacityUnits: Fn::GetOptionSetting: OptionName : SessionWriteCapacityUnits DefaultValue: 1 SessionWriteCapacityUnitsLimit: Type: AWS::CloudWatch::Alarm Properties: AlarmDescription: { "Fn::Join" : ["", [{ "Ref" : "AWSEBEnvironmentName" }, " write capacity limit on the session table." ]]} Namespace: "AWS/DynamoDB" MetricName: ConsumedWriteCapacityUnits Dimensions: - Name: TableName Value: { "Ref" : "SessionTable" } Statistic: Sum Period: 300 EvaluationPeriods: 12 Threshold: Fn::GetOptionSetting: OptionName : SessionWriteCapacityUnitsAlarmThreshold DefaultValue: 240 ComparisonOperator: GreaterThanThreshold AlarmActions: - Ref: SessionAlarmTopic InsufficientDataActions: - Ref: SessionAlarmTopic SessionReadCapacityUnitsLimit: Type: AWS::CloudWatch::Alarm Properties: AlarmDescription: { "Fn::Join" : ["", [{ "Ref" : "AWSEBEnvironmentName" }, " read capacity limit on the session table." ]]} Namespace: "AWS/DynamoDB" MetricName: ConsumedReadCapacityUnits Dimensions: - Name: TableName Value: { "Ref" : "SessionTable" } Statistic: Sum Period: 300 EvaluationPeriods: 12 Threshold: Fn::GetOptionSetting: OptionName : SessionReadCapacityUnitsAlarmThreshold DefaultValue: 240 ComparisonOperator: GreaterThanThreshold AlarmActions: - Ref: SessionAlarmTopic InsufficientDataActions: - Ref: SessionAlarmTopic SessionThrottledRequestsAlarm: Type: AWS::CloudWatch::Alarm Properties: AlarmDescription: { "Fn::Join" : ["", [{ "Ref" : "AWSEBEnvironmentName" }, ": requests are being throttled." ]]} Namespace: AWS/DynamoDB MetricName: ThrottledRequests Dimensions: - Name: TableName Value: { "Ref" : "SessionTable" } Statistic: Sum Period: 300 EvaluationPeriods: 1 Threshold: Fn::GetOptionSetting: OptionName: SessionThrottledRequestsThreshold DefaultValue: 1 ComparisonOperator: GreaterThanThreshold AlarmActions: - Ref: SessionAlarmTopic InsufficientDataActions: - Ref: SessionAlarmTopic SessionAlarmTopic: Type: AWS::SNS::Topic Properties: Subscription: - Endpoint: Fn::GetOptionSetting: OptionName: SessionAlarmEmail DefaultValue: "nobody@amazon.com" Protocol: email files: "/var/app/sessiontable": mode: "000444" content: | `{"Ref" : "SessionTable"}` `{"Ref" : "AWS::Region"}` "/var/app/composer.json": mode: "000744" content: { "require": { "aws/aws-sdk-php": "*" } } container_commands: "1-install-composer": command: "cd /var/app; curl -s http://getcomposer.org/installer | php" "2-install-dependencies": command: "cd /var/app; php composer.phar install" "3-cleanup-composer": command: "rm -Rf /var/app/composer.*"

在示例配置文件中,我们首先创建 DynamoDB 表,并配置该表的主密钥结构和容量单位,以便分配足够的资源提供所要求的吞吐量。下一步,我们为 WriteCapacityReadCapacity 创建 CloudWatch 警报。我们会创建 SNS 主题,该主题会在警报阈值被突破时将电子邮件发送到“nobody@amazon.com”。

在为环境创建和配置 AWS 资源后,需要自定义 EC2 实例。我们使用 files 密钥将 DynamoDB 的详细信息传递给环境中的 EC2 实例,并给适用于 PHP 的 AWS 开发工具包 2 的 composer.json 文件添加“require”。最后,我们会运行容器命令安装编辑器和必需的依赖项,然后删除安装程序。

.ebextensions/options.config

option_settings: "aws:elasticbeanstalk:customoption": SessionHashKeyName : username SessionHashKeyType : S SessionReadCapacityUnits : 1 SessionReadCapacityUnitsAlarmThreshold : 240 SessionWriteCapacityUnits : 1 SessionWriteCapacityUnitsAlarmThreshold : 240 SessionThrottledRequestsThreshold : 1 SessionAlarmEmail : me@example.com

使用您希望收到的警报通知的电子邮件地址取代 SessionAlarmEmail 值。options.config 文件包含 dynamodb.config 中用于定义的部分变量的值。例如,dynamodb.config 包含以下行:

Subscription: - Endpoint: Fn::GetOptionSetting: OptionName: SessionAlarmEmail DefaultValue: "nobody@amazon.com"

这些行会指示 Elastic Beanstalk 从配置文件(示例应用程序中为 options.config)的 SessionAlarmEmail 值中获取 Endpoint 属性的值,该配置文件的 option_settings 部分带有 aws:elasticbeanstalk:customoption 部分,后者的名称-值对中包含了实际要使用的值。在以上示例中,这意味着 SessionAlarmEmail 将被分配 nobody@amazon.com 值。

有关此示例中使用的 CloudFormation 资源的详细信息,请参阅以下参考: