Esempio: DynamoDB, CloudWatch e SNS - AWS Elastic Beanstalk

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Esempio: DynamoDB, CloudWatch e SNS

Questo file di configurazione configura la tabella DynamoDB come gestore di sessione per un'applicazione basata su PHP mediante AWS SDK for PHP 2. Per utilizzare questo esempio, è necessario disporre di un profilo dell'istanza IAM, che viene aggiunto alle istanze nell'ambiente e utilizzato per accedere alla tabella DynamoDB.

Puoi scaricare l'esempio che utilizzeremo in questa fase facendo clic su DynamoDB session Support example. L'esempio contiene i file seguenti:

  • L'applicazione d'esempio, ., index.php

  • Un file di configurazione, dynamodb.config, per creare e configurare una tabella DynamoDB e altre risorse AWS, nonché per installare software sulle istanze EC2 che ospitano l'applicazione in un ambiente Elastic Beanstalk.

  • Un file di configurazione, options.config, che sovrascrive le impostazioni di default in dynamodb.config con impostazioni specifiche per questa particolare installazione.

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="https://aws.amazon.com/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.*"

Nel file di configurazione di esempio, creiamo dapprima la tabella DynamoDB e configuriamo la struttura della chiave primaria per la tabella e le unità di capacità per allocare risorse sufficienti e fornire il throughput richiesto. Successivamente, creiamo allarmi CloudWatch per WriteCapacity e ReadCapacity e quindi un argomento SNS che invia e-mail a "nobody@amazon.com" se le soglie di allarme vengono superate.

Dopo la creazione e la configurazione delle risorse AWS per l'ambiente, è necessario personalizzare le istanze EC2. Utilizziamo la chiave files per passare i dettagli della tabella DynamoDB alle istanze EC2 nell'ambiente e aggiungere una chiave "require" nel file composer.json per AWS SDK for PHP 2. Eseguiamo, infine, i comandi contenitore per installare Composer, le dipendenze necessarie e quindi rimuovere il programma di installazione.

.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

Sostituisci il valore SessionAlarmEmail con l'e-mail dove vuoi ricevere le notifiche di allarme. Il file options.config contiene i valori utilizzati per alcune delle variabili definite in dynamodb.config. Ad esempio, dynamodb.config contiene le seguenti righe:

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

Con queste righe, Elastic Beanstalk recupera il valore della proprietà Endpoint dal valore SessionAlarmEmail in un file di configurazione (options.config nella nostra applicazione di esempio) che contiene una sezione option_settings con una sezione aws:elasticbeanstalk:customoption contenente una coppia nome-valore che include il valore effettivo da utilizzare. Nell'esempio precedente, a SessionAlarmEmail sarebbe quindi assegnato il valore nobody@amazon.com.

Per ulteriori informazioni sulle risorse CloudFormation utilizzate in questo esempio, consulta: