예: DynamoDB, CloudWatch, SNS - AWS Elastic Beanstalk

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

예: DynamoDB, CloudWatch, SNS

이 구성 파일은 PHP 2용 AWS SDK를 사용하여 DynamoDB 테이블을 PHP 기반 애플리케이션의 세션 핸들러로 설정합니다. 이 예를 사용하려면 환경의 인스턴스에 추가되고 DynamoDB 테이블에 액세스하는 데 사용하는 IAM 인스턴스 프로파일이 있어야 합니다.

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="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.*"

샘플 구성 파일에서는 먼저 DynamoDB 테이블을 만든 후 충분한 리소스를 할당하도록 테이블과 용량 단위의 기본 키 구조를 구성하여 요청한 처리량을 제공합니다. 그런 다음 WriteCapacityReadCapacity에 대한 CloudWatch 경보를 만듭니다. 경보 임계값을 초과하면 "nobody@amazon.com"에 이메일을 보내는 SNS 주제를 만듭니다.

환경의 AWS 리소스를 만들고 구성한 후 EC2 인스턴스를 사용자 지정해야 합니다. files 키를 사용하여 DynamoDB 테이블의 세부 정보를 환경의 EC2 인스턴스에 전달하고, PHP 2용 AWS SDK의 composer.json 파일에 "require"를 추가합니다. 마지막으로 컨테이너 명령을 실행하여 composer와 필요한 종속 항목을 설치한 후 설치 관리자를 제거합니다.

.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"

이러한 행은 사용할 실제 값의 이름-값 페어가 포함된 aws:elasticbeanstalk:customoption 섹션과 함께 option_settings 섹션이 포함된 구성 파일(샘플 애플리케이션의 options.config)의 SessionAlarmEmail 값에서 Endpoint 속성의 값을 가져오라고 Elastic Beanstalk에 지시합니다. 위 예에서 이는 SessionAlarmEmail이 값 nobody@amazon.com을 할당할 것임을 의미합니다.

이 예에서 사용된 CloudFormation 리소스에 대한 자세한 내용은 다음 참조를 참조하십시오.