文件 AWS SDK AWS 範例 SDK 儲存庫中有更多可用的
本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
使用 SDK for Word 的 Lambda 範例 PHP
下列程式碼範例示範如何搭配 AWS SDK for PHP Lambda 使用 來執行動作和實作常見案例。
基本概念是程式碼範例,示範如何在服務內執行基本操作。
Actions 是大型程式的程式碼摘錄,必須在內容中執行。雖然 動作會示範如何呼叫個別服務函數,但您可以在其相關案例中查看內容中的動作。
案例是程式碼範例,示範如何透過呼叫服務內的多個函數或與其他函數結合來完成特定任務 AWS 服務。
每個範例都包含完整原始程式碼的連結,您可以在其中找到如何在內容中設定和執行程式碼的指示。
基本概念
以下程式碼範例顯示做法:
建立 IAM 角色和 Lambda 函數,然後上傳處理常式程式碼。
調用具有單一參數的函數並取得結果。
更新函數程式碼並使用環境變數進行設定。
調用具有新參數的函數並取得結果。顯示傳回的執行日誌。
列出您帳戶的函數,然後清理相關資源。
如需詳細資訊,請參閱使用主控台建立 Lambda 函數。
- 適用於 PHP 的 SDK
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 namespace Lambda; use Aws\S3\S3Client; use GuzzleHttp\Psr7\Stream; use Iam\IAMService; class GettingStartedWithLambda { public function run() { echo("\n"); echo("--------------------------------------\n"); print("Welcome to the AWS Lambda getting started demo using PHP!\n"); echo("--------------------------------------\n"); $clientArgs = [ 'region' => 'us-west-2', 'version' => 'latest', 'profile' => 'default', ]; $uniqid = uniqid(); $iamService = new IAMService(); $s3client = new S3Client($clientArgs); $lambdaService = new LambdaService(); echo "First, let's create a role to run our Lambda code.\n"; $roleName = "test-lambda-role-$uniqid"; $rolePolicyDocument = "{ \"Version\": \"2012-10-17\", \"Statement\": [ { \"Effect\": \"Allow\", \"Principal\": { \"Service\": \"lambda.amazonaws.com\" }, \"Action\": \"sts:AssumeRole\" } ] }"; $role = $iamService->createRole($roleName, $rolePolicyDocument); echo "Created role {$role['RoleName']}.\n"; $iamService->attachRolePolicy( $role['RoleName'], "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" ); echo "Attached the AWSLambdaBasicExecutionRole to {$role['RoleName']}.\n"; echo "\nNow let's create an S3 bucket and upload our Lambda code there.\n"; $bucketName = "test-example-bucket-$uniqid"; $s3client->createBucket([ 'Bucket' => $bucketName, ]); echo "Created bucket $bucketName.\n"; $functionName = "doc_example_lambda_$uniqid"; $codeBasic = __DIR__ . "/lambda_handler_basic.zip"; $handler = "lambda_handler_basic"; $file = file_get_contents($codeBasic); $s3client->putObject([ 'Bucket' => $bucketName, 'Key' => $functionName, 'Body' => $file, ]); echo "Uploaded the Lambda code.\n"; $createLambdaFunction = $lambdaService->createFunction($functionName, $role, $bucketName, $handler); // Wait until the function has finished being created. do { $getLambdaFunction = $lambdaService->getFunction($createLambdaFunction['FunctionName']); } while ($getLambdaFunction['Configuration']['State'] == "Pending"); echo "Created Lambda function {$getLambdaFunction['Configuration']['FunctionName']}.\n"; sleep(1); echo "\nOk, let's invoke that Lambda code.\n"; $basicParams = [ 'action' => 'increment', 'number' => 3, ]; /** @var Stream $invokeFunction */ $invokeFunction = $lambdaService->invoke($functionName, $basicParams)['Payload']; $result = json_decode($invokeFunction->getContents())->result; echo "After invoking the Lambda code with the input of {$basicParams['number']} we received $result.\n"; echo "\nSince that's working, let's update the Lambda code.\n"; $codeCalculator = "lambda_handler_calculator.zip"; $handlerCalculator = "lambda_handler_calculator"; echo "First, put the new code into the S3 bucket.\n"; $file = file_get_contents($codeCalculator); $s3client->putObject([ 'Bucket' => $bucketName, 'Key' => $functionName, 'Body' => $file, ]); echo "New code uploaded.\n"; $lambdaService->updateFunctionCode($functionName, $bucketName, $functionName); // Wait for the Lambda code to finish updating. do { $getLambdaFunction = $lambdaService->getFunction($createLambdaFunction['FunctionName']); } while ($getLambdaFunction['Configuration']['LastUpdateStatus'] !== "Successful"); echo "New Lambda code uploaded.\n"; $environment = [ 'Variable' => ['Variables' => ['LOG_LEVEL' => 'DEBUG']], ]; $lambdaService->updateFunctionConfiguration($functionName, $handlerCalculator, $environment); do { $getLambdaFunction = $lambdaService->getFunction($createLambdaFunction['FunctionName']); } while ($getLambdaFunction['Configuration']['LastUpdateStatus'] !== "Successful"); echo "Lambda code updated with new handler and a LOG_LEVEL of DEBUG for more information.\n"; echo "Invoke the new code with some new data.\n"; $calculatorParams = [ 'action' => 'plus', 'x' => 5, 'y' => 4, ]; $invokeFunction = $lambdaService->invoke($functionName, $calculatorParams, "Tail"); $result = json_decode($invokeFunction['Payload']->getContents())->result; echo "Indeed, {$calculatorParams['x']} + {$calculatorParams['y']} does equal $result.\n"; echo "Here's the extra debug info: "; echo base64_decode($invokeFunction['LogResult']) . "\n"; echo "\nBut what happens if you try to divide by zero?\n"; $divZeroParams = [ 'action' => 'divide', 'x' => 5, 'y' => 0, ]; $invokeFunction = $lambdaService->invoke($functionName, $divZeroParams, "Tail"); $result = json_decode($invokeFunction['Payload']->getContents())->result; echo "You get a |$result| result.\n"; echo "And an error message: "; echo base64_decode($invokeFunction['LogResult']) . "\n"; echo "\nHere's all the Lambda functions you have in this Region:\n"; $listLambdaFunctions = $lambdaService->listFunctions(5); $allLambdaFunctions = $listLambdaFunctions['Functions']; $next = $listLambdaFunctions->get('NextMarker'); while ($next != false) { $listLambdaFunctions = $lambdaService->listFunctions(5, $next); $next = $listLambdaFunctions->get('NextMarker'); $allLambdaFunctions = array_merge($allLambdaFunctions, $listLambdaFunctions['Functions']); } foreach ($allLambdaFunctions as $function) { echo "{$function['FunctionName']}\n"; } echo "\n\nAnd don't forget to clean up your data!\n"; $lambdaService->deleteFunction($functionName); echo "Deleted Lambda function.\n"; $iamService->deleteRole($role['RoleName']); echo "Deleted Role.\n"; $deleteObjects = $s3client->listObjectsV2([ 'Bucket' => $bucketName, ]); $deleteObjects = $s3client->deleteObjects([ 'Bucket' => $bucketName, 'Delete' => [ 'Objects' => $deleteObjects['Contents'], ] ]); echo "Deleted all objects from the S3 bucket.\n"; $s3client->deleteBucket(['Bucket' => $bucketName]); echo "Deleted the bucket.\n"; } }
-
如需 API 詳細資訊,請參閱 AWS SDK for PHP API 參考中的下列主題。
-
動作
下列程式碼範例示範如何使用 CreateFunction
。
- 適用於 PHP 的 SDK
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 public function createFunction($functionName, $role, $bucketName, $handler) { //This assumes the Lambda function is in an S3 bucket. return $this->customWaiter(function () use ($functionName, $role, $bucketName, $handler) { return $this->lambdaClient->createFunction([ 'Code' => [ 'S3Bucket' => $bucketName, 'S3Key' => $functionName, ], 'FunctionName' => $functionName, 'Role' => $role['Arn'], 'Runtime' => 'python3.9', 'Handler' => "$handler.lambda_handler", ]); }); }
-
如需 API 詳細資訊,請參閱 CreateFunction AWS SDK for PHP 參考中的 API。
-
下列程式碼範例示範如何使用 DeleteFunction
。
- 適用於 PHP 的 SDK
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 public function deleteFunction($functionName) { return $this->lambdaClient->deleteFunction([ 'FunctionName' => $functionName, ]); }
-
如需 API 詳細資訊,請參閱 DeleteFunction AWS SDK for PHP 參考中的 API。
-
下列程式碼範例示範如何使用 GetFunction
。
- 適用於 PHP 的 SDK
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 public function getFunction($functionName) { return $this->lambdaClient->getFunction([ 'FunctionName' => $functionName, ]); }
-
如需 API 詳細資訊,請參閱 GetFunction AWS SDK for PHP 參考中的 API。
-
下列程式碼範例示範如何使用 Invoke
。
- 適用於 PHP 的 SDK
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 public function invoke($functionName, $params, $logType = 'None') { return $this->lambdaClient->invoke([ 'FunctionName' => $functionName, 'Payload' => json_encode($params), 'LogType' => $logType, ]); }
-
如需 API 詳細資訊,請參閱在 Word 參考中叫用。 AWS SDK for PHP API
-
下列程式碼範例示範如何使用 ListFunctions
。
- 適用於 PHP 的 SDK
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 public function listFunctions($maxItems = 50, $marker = null) { if (is_null($marker)) { return $this->lambdaClient->listFunctions([ 'MaxItems' => $maxItems, ]); } return $this->lambdaClient->listFunctions([ 'Marker' => $marker, 'MaxItems' => $maxItems, ]); }
-
如需 API 詳細資訊,請參閱 ListFunctions AWS SDK for PHP 參考中的 API。
-
下列程式碼範例示範如何使用 UpdateFunctionCode
。
- 適用於 PHP 的 SDK
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 public function updateFunctionCode($functionName, $s3Bucket, $s3Key) { return $this->lambdaClient->updateFunctionCode([ 'FunctionName' => $functionName, 'S3Bucket' => $s3Bucket, 'S3Key' => $s3Key, ]); }
-
如需 API 詳細資訊,請參閱 UpdateFunctionCode AWS SDK for PHP 參考中的 API。
-
下列程式碼範例示範如何使用 UpdateFunctionConfiguration
。
- 適用於 PHP 的 SDK
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 public function updateFunctionConfiguration($functionName, $handler, $environment = '') { return $this->lambdaClient->updateFunctionConfiguration([ 'FunctionName' => $functionName, 'Handler' => "$handler.lambda_handler", 'Environment' => $environment, ]); }
-
如需 API 詳細資訊,請參閱 UpdateFunctionConfiguration AWS SDK for PHP 參考中的 API。
-
案例
下列程式碼範例示範如何建立無伺服器應用程式,讓使用者以標籤管理相片。
無伺服器範例
下列程式碼範例示範如何實作連線至 RDS 資料庫的 Lambda 函數。函數會提出簡單的資料庫請求並傳回結果。
- 適用於 PHP 的 SDK
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在無伺服器範例
儲存庫中設定和執行。 使用 RDS 連線至 Lambda 函數中的 Amazon PHP 資料庫。
<?php # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 # using bref/bref and bref/logger for simplicity use Bref\Context\Context; use Bref\Event\Handler as StdHandler; use Bref\Logger\StderrLogger; use Aws\Rds\AuthTokenGenerator; use Aws\Credentials\CredentialProvider; require __DIR__ . '/vendor/autoload.php'; class Handler implements StdHandler { private StderrLogger $logger; public function __construct(StderrLogger $logger) { $this->logger = $logger; } private function getAuthToken(): string { // Define connection authentication parameters $dbConnection = [ 'hostname' => getenv('DB_HOSTNAME'), 'port' => getenv('DB_PORT'), 'username' => getenv('DB_USERNAME'), 'region' => getenv('AWS_REGION'), ]; // Create RDS AuthTokenGenerator object $generator = new AuthTokenGenerator(CredentialProvider::defaultProvider()); // Request authorization token from RDS, specifying the username return $generator->createToken( $dbConnection['hostname'] . ':' . $dbConnection['port'], $dbConnection['region'], $dbConnection['username'] ); } private function getQueryResults() { // Obtain auth token $token = $this->getAuthToken(); // Define connection configuration $connectionConfig = [ 'host' => getenv('DB_HOSTNAME'), 'user' => getenv('DB_USERNAME'), 'password' => $token, 'database' => getenv('DB_NAME'), ]; // Create the connection to the DB $conn = new PDO( "mysql:host={$connectionConfig['host']};dbname={$connectionConfig['database']}", $connectionConfig['user'], $connectionConfig['password'], [ PDO::MYSQL_ATTR_SSL_CA => '/path/to/rds-ca-2019-root.pem', PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT => true, ] ); // Obtain the result of the query $stmt = $conn->prepare('SELECT ?+? AS sum'); $stmt->execute([3, 2]); return $stmt->fetch(PDO::FETCH_ASSOC); } /** * @param mixed $event * @param Context $context * @return array */ public function handle(mixed $event, Context $context): array { $this->logger->info("Processing query"); // Execute database flow $result = $this->getQueryResults(); return [ 'sum' => $result['sum'] ]; } } $logger = new StderrLogger(); return new Handler($logger);
下列程式碼範例示範如何實作 Lambda 函數,該函數接收從 Kinesis 串流接收記錄所觸發的事件。此函數會擷取 Kinesis 承載、從 Base64 解碼,並記錄記錄內容。
- 適用於 PHP 的 SDK
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在無伺服器範例
儲存庫中設定和執行。 使用 PHP 搭配 Lambda 使用 Kinesis 事件。
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 <?php # using bref/bref and bref/logger for simplicity use Bref\Context\Context; use Bref\Event\Kinesis\KinesisEvent; use Bref\Event\Kinesis\KinesisHandler; use Bref\Logger\StderrLogger; require __DIR__ . '/vendor/autoload.php'; class Handler extends KinesisHandler { private StderrLogger $logger; public function __construct(StderrLogger $logger) { $this->logger = $logger; } /** * @throws JsonException * @throws \Bref\Event\InvalidLambdaEvent */ public function handleKinesis(KinesisEvent $event, Context $context): void { $this->logger->info("Processing records"); $records = $event->getRecords(); foreach ($records as $record) { $data = $record->getData(); $this->logger->info(json_encode($data)); // TODO: Do interesting work based on the new data // Any exception thrown will be logged and the invocation will be marked as failed } $totalRecords = count($records); $this->logger->info("Successfully processed $totalRecords records"); } } $logger = new StderrLogger(); return new Handler($logger);
下列程式碼範例示範如何實作 Lambda 函數,該函數接收從 DynamoDB 串流接收記錄所觸發的事件。函數會擷取 DynamoDB 承載並記錄記錄內容。
- 適用於 PHP 的 SDK
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在無伺服器範例
儲存庫中設定和執行。 使用 PHP 搭配 Lambda 使用 DynamoDB 事件。
<?php # using bref/bref and bref/logger for simplicity use Bref\Context\Context; use Bref\Event\DynamoDb\DynamoDbEvent; use Bref\Event\DynamoDb\DynamoDbHandler; use Bref\Logger\StderrLogger; require __DIR__ . '/vendor/autoload.php'; class Handler extends DynamoDbHandler { private StderrLogger $logger; public function __construct(StderrLogger $logger) { $this->logger = $logger; } /** * @throws JsonException * @throws \Bref\Event\InvalidLambdaEvent */ public function handleDynamoDb(DynamoDbEvent $event, Context $context): void { $this->logger->info("Processing DynamoDb table items"); $records = $event->getRecords(); foreach ($records as $record) { $eventName = $record->getEventName(); $keys = $record->getKeys(); $old = $record->getOldImage(); $new = $record->getNewImage(); $this->logger->info("Event Name:".$eventName."\n"); $this->logger->info("Keys:". json_encode($keys)."\n"); $this->logger->info("Old Image:". json_encode($old)."\n"); $this->logger->info("New Image:". json_encode($new)); // TODO: Do interesting work based on the new data // Any exception thrown will be logged and the invocation will be marked as failed } $totalRecords = count($records); $this->logger->info("Successfully processed $totalRecords items"); } } $logger = new StderrLogger(); return new Handler($logger);
下列程式碼範例示範如何實作 Lambda 函數,該函數接收從 DocumentDB 變更串流接收記錄所觸發的事件。函數會擷取 DocumentDB 承載並記錄記錄內容。
- 適用於 PHP 的 SDK
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在無伺服器範例
儲存庫中設定和執行。 使用 PHP 搭配 Lambda 使用 Amazon DocumentDB 事件。
<?php require __DIR__.'/vendor/autoload.php'; use Bref\Context\Context; use Bref\Event\Handler; class DocumentDBEventHandler implements Handler { public function handle($event, Context $context): string { $events = $event['events'] ?? []; foreach ($events as $record) { $this->logDocumentDBEvent($record['event']); } return 'OK'; } private function logDocumentDBEvent($event): void { // Extract information from the event record $operationType = $event['operationType'] ?? 'Unknown'; $db = $event['ns']['db'] ?? 'Unknown'; $collection = $event['ns']['coll'] ?? 'Unknown'; $fullDocument = $event['fullDocument'] ?? []; // Log the event details echo "Operation type: $operationType\n"; echo "Database: $db\n"; echo "Collection: $collection\n"; echo "Full document: " . json_encode($fullDocument, JSON_PRETTY_PRINT) . "\n"; } } return new DocumentDBEventHandler();
下列程式碼範例示範如何實作 Lambda 函數,該函數接收從 Amazon MSK 叢集接收記錄所觸發的事件。函數會擷取 MSK 承載並記錄記錄內容。
- 適用於 PHP 的 SDK
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在無伺服器範例
儲存庫中設定和執行。 使用 MSK 搭配 Lambda 使用 Amazon PHP 事件。
<?php // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // using bref/bref and bref/logger for simplicity use Bref\Context\Context; use Bref\Event\Kafka\KafkaEvent; use Bref\Event\Handler as StdHandler; use Bref\Logger\StderrLogger; require __DIR__ . '/vendor/autoload.php'; class Handler implements StdHandler { private StderrLogger $logger; public function __construct(StderrLogger $logger) { $this->logger = $logger; } /** * @throws JsonException * @throws \Bref\Event\InvalidLambdaEvent */ public function handle(mixed $event, Context $context): void { $kafkaEvent = new KafkaEvent($event); $this->logger->info("Processing records"); $records = $kafkaEvent->getRecords(); foreach ($records as $record) { try { $key = $record->getKey(); $this->logger->info("Key: $key"); $values = $record->getValue(); $this->logger->info(json_encode($values)); foreach ($values as $value) { $this->logger->info("Value: $value"); } } catch (Exception $e) { $this->logger->error($e->getMessage()); } } $totalRecords = count($records); $this->logger->info("Successfully processed $totalRecords records"); } } $logger = new StderrLogger(); return new Handler($logger);
下列程式碼範例示範如何實作 Lambda 函數,該函數接收透過將物件上傳至 S3 儲存貯體所觸發的事件。函數會從事件參數擷取 S3 儲存貯體名稱和物件金鑰,並呼叫 Amazon S3 API 來擷取和記錄物件的內容類型。
- 適用於 PHP 的 SDK
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在無伺服器範例
儲存庫中設定和執行。 使用 PHP 搭配 Lambda 使用 S3 事件。
<?php use Bref\Context\Context; use Bref\Event\S3\S3Event; use Bref\Event\S3\S3Handler; use Bref\Logger\StderrLogger; require __DIR__ . '/vendor/autoload.php'; class Handler extends S3Handler { private StderrLogger $logger; public function __construct(StderrLogger $logger) { $this->logger = $logger; } public function handleS3(S3Event $event, Context $context) : void { $this->logger->info("Processing S3 records"); // Get the object from the event and show its content type $records = $event->getRecords(); foreach ($records as $record) { $bucket = $record->getBucket()->getName(); $key = urldecode($record->getObject()->getKey()); try { $fileSize = urldecode($record->getObject()->getSize()); echo "File Size: " . $fileSize . "\n"; // TODO: Implement your custom processing logic here } catch (Exception $e) { echo $e->getMessage() . "\n"; echo 'Error getting object ' . $key . ' from bucket ' . $bucket . '. Make sure they exist and your bucket is in the same region as this function.' . "\n"; throw $e; } } } } $logger = new StderrLogger(); return new Handler($logger);
下列程式碼範例示範如何實作 Lambda 函數,該函數接收從 SNS 主題接收訊息所觸發的事件。函數會從事件參數擷取訊息,並記錄每一則訊息的內容。
- 適用於 PHP 的 SDK
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在無伺服器範例
儲存庫中設定和執行。 使用 SNS 搭配 Lambda 使用 PHP 事件。
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 <?php /* Since native PHP support for AWS Lambda is not available, we are utilizing Bref's PHP functions runtime for AWS Lambda. For more information on Bref's PHP runtime for Lambda, refer to: https://bref.sh/docs/runtimes/function Another approach would be to create a custom runtime. A practical example can be found here: https://aws.amazon.com/blogs/apn/aws-lambda-custom-runtime-for-php-a-practical-example/ */ // Additional composer packages may be required when using Bref or any other PHP functions runtime. // require __DIR__ . '/vendor/autoload.php'; use Bref\Context\Context; use Bref\Event\Sns\SnsEvent; use Bref\Event\Sns\SnsHandler; class Handler extends SnsHandler { public function handleSns(SnsEvent $event, Context $context): void { foreach ($event->getRecords() as $record) { $message = $record->getMessage(); // TODO: Implement your custom processing logic here // Any exception thrown will be logged and the invocation will be marked as failed echo "Processed Message: $message" . PHP_EOL; } } } return new Handler();
下列程式碼範例示範如何實作 Lambda 函數,該函數接收從 SQS 佇列接收訊息所觸發的事件。函數會從事件參數擷取訊息,並記錄每一則訊息的內容。
- 適用於 PHP 的 SDK
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在無伺服器範例
儲存庫中設定和執行。 使用 SQS 搭配 Lambda 使用 PHP 事件。
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 <?php # using bref/bref and bref/logger for simplicity use Bref\Context\Context; use Bref\Event\InvalidLambdaEvent; use Bref\Event\Sqs\SqsEvent; use Bref\Event\Sqs\SqsHandler; use Bref\Logger\StderrLogger; require __DIR__ . '/vendor/autoload.php'; class Handler extends SqsHandler { private StderrLogger $logger; public function __construct(StderrLogger $logger) { $this->logger = $logger; } /** * @throws InvalidLambdaEvent */ public function handleSqs(SqsEvent $event, Context $context): void { foreach ($event->getRecords() as $record) { $body = $record->getBody(); // TODO: Do interesting work based on the new message } } } $logger = new StderrLogger(); return new Handler($logger);
下列程式碼範例示範如何針對從 Kinesis 串流接收事件的 Lambda 函數實作部分批次回應。此函數會在回應中報告批次項目失敗,指示 Lambda 稍後重試這些訊息。
- 適用於 PHP 的 SDK
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在無伺服器範例
儲存庫中設定和執行。 使用 PHP 向 Lambda 報告 Kinesis 批次項目失敗。
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 <?php # using bref/bref and bref/logger for simplicity use Bref\Context\Context; use Bref\Event\Kinesis\KinesisEvent; use Bref\Event\Handler as StdHandler; use Bref\Logger\StderrLogger; require __DIR__ . '/vendor/autoload.php'; class Handler implements StdHandler { private StderrLogger $logger; public function __construct(StderrLogger $logger) { $this->logger = $logger; } /** * @throws JsonException * @throws \Bref\Event\InvalidLambdaEvent */ public function handle(mixed $event, Context $context): array { $kinesisEvent = new KinesisEvent($event); $this->logger->info("Processing records"); $records = $kinesisEvent->getRecords(); $failedRecords = []; foreach ($records as $record) { try { $data = $record->getData(); $this->logger->info(json_encode($data)); // TODO: Do interesting work based on the new data } catch (Exception $e) { $this->logger->error($e->getMessage()); // failed processing the record $failedRecords[] = $record->getSequenceNumber(); } } $totalRecords = count($records); $this->logger->info("Successfully processed $totalRecords records"); // change format for the response $failures = array_map( fn(string $sequenceNumber) => ['itemIdentifier' => $sequenceNumber], $failedRecords ); return [ 'batchItemFailures' => $failures ]; } } $logger = new StderrLogger(); return new Handler($logger);
下列程式碼範例示範如何針對從 DynamoDB 串流接收事件的 Lambda 函數實作部分批次回應。此函數會在回應中報告批次項目失敗,指示 Lambda 稍後重試這些訊息。
- 適用於 PHP 的 SDK
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在無伺服器範例
儲存庫中設定和執行。 使用 PHP 使用 Lambda 報告 DynamoDB 批次項目失敗。
<?php # using bref/bref and bref/logger for simplicity use Bref\Context\Context; use Bref\Event\DynamoDb\DynamoDbEvent; use Bref\Event\Handler as StdHandler; use Bref\Logger\StderrLogger; require __DIR__ . '/vendor/autoload.php'; class Handler implements StdHandler { private StderrLogger $logger; public function __construct(StderrLogger $logger) { $this->logger = $logger; } /** * @throws JsonException * @throws \Bref\Event\InvalidLambdaEvent */ public function handle(mixed $event, Context $context): array { $dynamoDbEvent = new DynamoDbEvent($event); $this->logger->info("Processing records"); $records = $dynamoDbEvent->getRecords(); $failedRecords = []; foreach ($records as $record) { try { $data = $record->getData(); $this->logger->info(json_encode($data)); // TODO: Do interesting work based on the new data } catch (Exception $e) { $this->logger->error($e->getMessage()); // failed processing the record $failedRecords[] = $record->getSequenceNumber(); } } $totalRecords = count($records); $this->logger->info("Successfully processed $totalRecords records"); // change format for the response $failures = array_map( fn(string $sequenceNumber) => ['itemIdentifier' => $sequenceNumber], $failedRecords ); return [ 'batchItemFailures' => $failures ]; } } $logger = new StderrLogger(); return new Handler($logger);
下列程式碼範例示範如何針對從 SQS 佇列接收事件的 Lambda 函數實作部分批次回應。此函數會在回應中報告批次項目失敗,指示 Lambda 稍後重試這些訊息。
- 適用於 PHP 的 SDK
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在無伺服器範例
儲存庫中設定和執行。 使用 SQS 使用 Lambda 報告 PHP 批次項目失敗。
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 <?php use Bref\Context\Context; use Bref\Event\Sqs\SqsEvent; use Bref\Event\Sqs\SqsHandler; use Bref\Logger\StderrLogger; require __DIR__ . '/vendor/autoload.php'; class Handler extends SqsHandler { private StderrLogger $logger; public function __construct(StderrLogger $logger) { $this->logger = $logger; } /** * @throws JsonException * @throws \Bref\Event\InvalidLambdaEvent */ public function handleSqs(SqsEvent $event, Context $context): void { $this->logger->info("Processing SQS records"); $records = $event->getRecords(); foreach ($records as $record) { try { // Assuming the SQS message is in JSON format $message = json_decode($record->getBody(), true); $this->logger->info(json_encode($message)); // TODO: Implement your custom processing logic here } catch (Exception $e) { $this->logger->error($e->getMessage()); // failed processing the record $this->markAsFailed($record); } } $totalRecords = count($records); $this->logger->info("Successfully processed $totalRecords SQS records"); } } $logger = new StderrLogger(); return new Handler($logger);