使用適用於 Ruby 的 SDK 的 Lambda 範例 - AWS 適用於 Ruby 的 SDK

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

使用適用於 Ruby 的 SDK 的 Lambda 範例

下列程式碼範例示範如何使用 AWS SDK for Ruby 搭配 Lambda 執行動作和實作常見案例。

基本概念是程式碼範例,這些範例說明如何在服務內執行基本操作。

Actions 是大型程式的程式碼摘錄,必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數,但您可以在其相關情境中查看內容中的動作。

案例是向您展示如何呼叫服務中的多個函數或與其他 AWS 服務組合來完成特定任務的程式碼範例。

每個範例都包含完整原始程式碼的連結,您可以在其中找到如何在內容中設定和執行程式碼的指示。

開始使用

下列程式碼範例示範如何開始使用 Lambda。

SDK for Ruby
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

require 'aws-sdk-lambda' # Creates an AWS Lambda client using the default credentials and configuration def lambda_client Aws::Lambda::Client.new end # Lists the Lambda functions in your AWS account, paginating the results if necessary def list_lambda_functions lambda = lambda_client # Use a pagination iterator to list all functions functions = [] lambda.list_functions.each_page do |page| functions.concat(page.functions) end # Print the name and ARN of each function functions.each do |function| puts "Function name: #{function.function_name}" puts "Function ARN: #{function.function_arn}" puts end puts "Total functions: #{functions.count}" end list_lambda_functions if __FILE__ == $PROGRAM_NAME
  • 如需 API 詳細資訊,請參閱《AWS SDK for Ruby API 參考》中的 ListFunctions

基本概念

以下程式碼範例顯示做法:

  • 建立 IAM 角色和 Lambda 函數,然後上傳處理常式程式碼。

  • 調用具有單一參數的函數並取得結果。

  • 更新函數程式碼並使用環境變數進行設定。

  • 調用具有新參數的函數並取得結果。顯示傳回的執行日誌。

  • 列出您帳戶的函數,然後清理相關資源。

如需詳細資訊,請參閱使用主控台建立 Lambda 函數

SDK for Ruby
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

為能夠寫入日誌的 Lambda 函數設定先決條件 IAM 許可。

# Get an AWS Identity and Access Management (IAM) role. # # @param iam_role_name: The name of the role to retrieve. # @param action: Whether to create or destroy the IAM apparatus. # @return: The IAM role. def manage_iam(iam_role_name, action) case action when 'create' create_iam_role(iam_role_name) when 'destroy' destroy_iam_role(iam_role_name) else raise "Incorrect action provided. Must provide 'create' or 'destroy'" end end private def create_iam_role(iam_role_name) role_policy = { 'Version': '2012-10-17', 'Statement': [ { 'Effect': 'Allow', 'Principal': { 'Service': 'lambda.amazonaws.com' }, 'Action': 'sts:AssumeRole' } ] } role = @iam_client.create_role( role_name: iam_role_name, assume_role_policy_document: role_policy.to_json ) @iam_client.attach_role_policy( { policy_arn: 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole', role_name: iam_role_name } ) wait_for_role_to_exist(iam_role_name) @logger.debug("Successfully created IAM role: #{role['role']['arn']}") sleep(10) [role, role_policy.to_json] end def destroy_iam_role(iam_role_name) @iam_client.detach_role_policy( { policy_arn: 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole', role_name: iam_role_name } ) @iam_client.delete_role(role_name: iam_role_name) @logger.debug("Detached policy & deleted IAM role: #{iam_role_name}") end def wait_for_role_to_exist(iam_role_name) @iam_client.wait_until(:role_exists, { role_name: iam_role_name }) do |w| w.max_attempts = 5 w.delay = 5 end end

定義 Lambda 處理常式,該處理常式以作為調用參數提供的數字遞增。

require 'logger' # A function that increments a whole number by one (1) and logs the result. # Requires a manually-provided runtime parameter, 'number', which must be Int # # @param event [Hash] Parameters sent when the function is invoked # @param context [Hash] Methods and properties that provide information # about the invocation, function, and execution environment. # @return incremented_number [String] The incremented number. def lambda_handler(event:, context:) logger = Logger.new($stdout) log_level = ENV['LOG_LEVEL'] logger.level = case log_level when 'debug' Logger::DEBUG when 'info' Logger::INFO else Logger::ERROR end logger.debug('This is a debug log message.') logger.info('This is an info log message. Code executed successfully!') number = event['number'].to_i incremented_number = number + 1 logger.info("You provided #{number.round} and it was incremented to #{incremented_number.round}") incremented_number.round.to_s end

將您的 Lambda 函數壓縮到部署套件中。

# Creates a Lambda deployment package in .zip format. # # @param source_file: The name of the object, without suffix, for the Lambda file and zip. # @return: The deployment package. def create_deployment_package(source_file) Dir.chdir(File.dirname(__FILE__)) if File.exist?('lambda_function.zip') File.delete('lambda_function.zip') @logger.debug('Deleting old zip: lambda_function.zip') end Zip::File.open('lambda_function.zip', create: true) do |zipfile| zipfile.add('lambda_function.rb', "#{source_file}.rb") end @logger.debug("Zipping #{source_file}.rb into: lambda_function.zip.") File.read('lambda_function.zip').to_s rescue StandardError => e @logger.error("There was an error creating deployment package:\n #{e.message}") end

建立新 Lambda 函數。

# Deploys a Lambda function. # # @param function_name: The name of the Lambda function. # @param handler_name: The fully qualified name of the handler function. # @param role_arn: The IAM role to use for the function. # @param deployment_package: The deployment package that contains the function code in .zip format. # @return: The Amazon Resource Name (ARN) of the newly created function. def create_function(function_name, handler_name, role_arn, deployment_package) response = @lambda_client.create_function({ role: role_arn.to_s, function_name: function_name, handler: handler_name, runtime: 'ruby2.7', code: { zip_file: deployment_package }, environment: { variables: { 'LOG_LEVEL' => 'info' } } }) @lambda_client.wait_until(:function_active_v2, { function_name: function_name }) do |w| w.max_attempts = 5 w.delay = 5 end response rescue Aws::Lambda::Errors::ServiceException => e @logger.error("There was an error creating #{function_name}:\n #{e.message}") rescue Aws::Waiters::Errors::WaiterFailed => e @logger.error("Failed waiting for #{function_name} to activate:\n #{e.message}") end

使用選用的執行階段參數調用 Lambda 函數。

# Invokes a Lambda function. # @param function_name [String] The name of the function to invoke. # @param payload [nil] Payload containing runtime parameters. # @return [Object] The response from the function invocation. def invoke_function(function_name, payload = nil) params = { function_name: function_name } params[:payload] = payload unless payload.nil? @lambda_client.invoke(params) rescue Aws::Lambda::Errors::ServiceException => e @logger.error("There was an error executing #{function_name}:\n #{e.message}") end

更新 Lambda 函數的組態以注入新的環境變數。

# Updates the environment variables for a Lambda function. # @param function_name: The name of the function to update. # @param log_level: The log level of the function. # @return: Data about the update, including the status. def update_function_configuration(function_name, log_level) @lambda_client.update_function_configuration({ function_name: function_name, environment: { variables: { 'LOG_LEVEL' => log_level } } }) @lambda_client.wait_until(:function_updated_v2, { function_name: function_name }) do |w| w.max_attempts = 5 w.delay = 5 end rescue Aws::Lambda::Errors::ServiceException => e @logger.error("There was an error updating configurations for #{function_name}:\n #{e.message}") rescue Aws::Waiters::Errors::WaiterFailed => e @logger.error("Failed waiting for #{function_name} to activate:\n #{e.message}") end

使用包含不同程式碼的不同部署套件來更新 Lambda 函數的程式碼。

# Updates the code for a Lambda function by submitting a .zip archive that contains # the code for the function. # # @param function_name: The name of the function to update. # @param deployment_package: The function code to update, packaged as bytes in # .zip format. # @return: Data about the update, including the status. def update_function_code(function_name, deployment_package) @lambda_client.update_function_code( function_name: function_name, zip_file: deployment_package ) @lambda_client.wait_until(:function_updated_v2, { function_name: function_name }) do |w| w.max_attempts = 5 w.delay = 5 end rescue Aws::Lambda::Errors::ServiceException => e @logger.error("There was an error updating function code for: #{function_name}:\n #{e.message}") nil rescue Aws::Waiters::Errors::WaiterFailed => e @logger.error("Failed waiting for #{function_name} to update:\n #{e.message}") end

使用內建分頁程式列出所有現有的 Lambda 函數。

# Lists the Lambda functions for the current account. def list_functions functions = [] @lambda_client.list_functions.each do |response| response['functions'].each do |function| functions.append(function['function_name']) end end functions rescue Aws::Lambda::Errors::ServiceException => e @logger.error("There was an error listing functions:\n #{e.message}") end

刪除特定 Lambda 函數。

# Deletes a Lambda function. # @param function_name: The name of the function to delete. def delete_function(function_name) print "Deleting function: #{function_name}..." @lambda_client.delete_function( function_name: function_name ) print 'Done!'.green rescue Aws::Lambda::Errors::ServiceException => e @logger.error("There was an error deleting #{function_name}:\n #{e.message}") end

動作

下列程式碼範例示範如何使用 CreateFunction

SDK for Ruby
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

class LambdaWrapper attr_accessor :lambda_client, :cloudwatch_client, :iam_client def initialize @lambda_client = Aws::Lambda::Client.new @cloudwatch_client = Aws::CloudWatchLogs::Client.new(region: 'us-east-1') @iam_client = Aws::IAM::Client.new(region: 'us-east-1') @logger = Logger.new($stdout) @logger.level = Logger::WARN end # Deploys a Lambda function. # # @param function_name: The name of the Lambda function. # @param handler_name: The fully qualified name of the handler function. # @param role_arn: The IAM role to use for the function. # @param deployment_package: The deployment package that contains the function code in .zip format. # @return: The Amazon Resource Name (ARN) of the newly created function. def create_function(function_name, handler_name, role_arn, deployment_package) response = @lambda_client.create_function({ role: role_arn.to_s, function_name: function_name, handler: handler_name, runtime: 'ruby2.7', code: { zip_file: deployment_package }, environment: { variables: { 'LOG_LEVEL' => 'info' } } }) @lambda_client.wait_until(:function_active_v2, { function_name: function_name }) do |w| w.max_attempts = 5 w.delay = 5 end response rescue Aws::Lambda::Errors::ServiceException => e @logger.error("There was an error creating #{function_name}:\n #{e.message}") rescue Aws::Waiters::Errors::WaiterFailed => e @logger.error("Failed waiting for #{function_name} to activate:\n #{e.message}") end
  • 如需 API 詳細資訊,請參閱《AWS SDK for Ruby API 參考》中的「CreateFunction」。

下列程式碼範例示範如何使用 DeleteFunction

SDK for Ruby
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

class LambdaWrapper attr_accessor :lambda_client, :cloudwatch_client, :iam_client def initialize @lambda_client = Aws::Lambda::Client.new @cloudwatch_client = Aws::CloudWatchLogs::Client.new(region: 'us-east-1') @iam_client = Aws::IAM::Client.new(region: 'us-east-1') @logger = Logger.new($stdout) @logger.level = Logger::WARN end # Deletes a Lambda function. # @param function_name: The name of the function to delete. def delete_function(function_name) print "Deleting function: #{function_name}..." @lambda_client.delete_function( function_name: function_name ) print 'Done!'.green rescue Aws::Lambda::Errors::ServiceException => e @logger.error("There was an error deleting #{function_name}:\n #{e.message}") end
  • 如需 API 詳細資訊,請參閱《AWS SDK for Ruby API 參考》中的 DeleteFunction

下列程式碼範例示範如何使用 GetFunction

SDK for Ruby
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

class LambdaWrapper attr_accessor :lambda_client, :cloudwatch_client, :iam_client def initialize @lambda_client = Aws::Lambda::Client.new @cloudwatch_client = Aws::CloudWatchLogs::Client.new(region: 'us-east-1') @iam_client = Aws::IAM::Client.new(region: 'us-east-1') @logger = Logger.new($stdout) @logger.level = Logger::WARN end # Gets data about a Lambda function. # # @param function_name: The name of the function. # @return response: The function data, or nil if no such function exists. def get_function(function_name) @lambda_client.get_function( { function_name: function_name } ) rescue Aws::Lambda::Errors::ResourceNotFoundException => e @logger.debug("Could not find function: #{function_name}:\n #{e.message}") nil end
  • 如需 API 詳細資訊,請參閱《AWS SDK for Ruby API 參考》中的 GetFunction

下列程式碼範例示範如何使用 Invoke

SDK for Ruby
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

class LambdaWrapper attr_accessor :lambda_client, :cloudwatch_client, :iam_client def initialize @lambda_client = Aws::Lambda::Client.new @cloudwatch_client = Aws::CloudWatchLogs::Client.new(region: 'us-east-1') @iam_client = Aws::IAM::Client.new(region: 'us-east-1') @logger = Logger.new($stdout) @logger.level = Logger::WARN end # Invokes a Lambda function. # @param function_name [String] The name of the function to invoke. # @param payload [nil] Payload containing runtime parameters. # @return [Object] The response from the function invocation. def invoke_function(function_name, payload = nil) params = { function_name: function_name } params[:payload] = payload unless payload.nil? @lambda_client.invoke(params) rescue Aws::Lambda::Errors::ServiceException => e @logger.error("There was an error executing #{function_name}:\n #{e.message}") end
  • 如需 API 的詳細資訊,請參閱《AWS SDK for Ruby API 參考》中的「Invoke」。

下列程式碼範例示範如何使用 ListFunctions

SDK for Ruby
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

class LambdaWrapper attr_accessor :lambda_client, :cloudwatch_client, :iam_client def initialize @lambda_client = Aws::Lambda::Client.new @cloudwatch_client = Aws::CloudWatchLogs::Client.new(region: 'us-east-1') @iam_client = Aws::IAM::Client.new(region: 'us-east-1') @logger = Logger.new($stdout) @logger.level = Logger::WARN end # Lists the Lambda functions for the current account. def list_functions functions = [] @lambda_client.list_functions.each do |response| response['functions'].each do |function| functions.append(function['function_name']) end end functions rescue Aws::Lambda::Errors::ServiceException => e @logger.error("There was an error listing functions:\n #{e.message}") end
  • 如需 API 詳細資訊,請參閱《AWS SDK for Ruby API 參考》中的 ListFunctions

下列程式碼範例示範如何使用 UpdateFunctionCode

SDK for Ruby
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

class LambdaWrapper attr_accessor :lambda_client, :cloudwatch_client, :iam_client def initialize @lambda_client = Aws::Lambda::Client.new @cloudwatch_client = Aws::CloudWatchLogs::Client.new(region: 'us-east-1') @iam_client = Aws::IAM::Client.new(region: 'us-east-1') @logger = Logger.new($stdout) @logger.level = Logger::WARN end # Updates the code for a Lambda function by submitting a .zip archive that contains # the code for the function. # # @param function_name: The name of the function to update. # @param deployment_package: The function code to update, packaged as bytes in # .zip format. # @return: Data about the update, including the status. def update_function_code(function_name, deployment_package) @lambda_client.update_function_code( function_name: function_name, zip_file: deployment_package ) @lambda_client.wait_until(:function_updated_v2, { function_name: function_name }) do |w| w.max_attempts = 5 w.delay = 5 end rescue Aws::Lambda::Errors::ServiceException => e @logger.error("There was an error updating function code for: #{function_name}:\n #{e.message}") nil rescue Aws::Waiters::Errors::WaiterFailed => e @logger.error("Failed waiting for #{function_name} to update:\n #{e.message}") end
  • 如需 API 詳細資訊,請參閱《AWS SDK for Ruby API 參考》中的 UpdateFunctionCode

下列程式碼範例示範如何使用 UpdateFunctionConfiguration

SDK for Ruby
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

class LambdaWrapper attr_accessor :lambda_client, :cloudwatch_client, :iam_client def initialize @lambda_client = Aws::Lambda::Client.new @cloudwatch_client = Aws::CloudWatchLogs::Client.new(region: 'us-east-1') @iam_client = Aws::IAM::Client.new(region: 'us-east-1') @logger = Logger.new($stdout) @logger.level = Logger::WARN end # Updates the environment variables for a Lambda function. # @param function_name: The name of the function to update. # @param log_level: The log level of the function. # @return: Data about the update, including the status. def update_function_configuration(function_name, log_level) @lambda_client.update_function_configuration({ function_name: function_name, environment: { variables: { 'LOG_LEVEL' => log_level } } }) @lambda_client.wait_until(:function_updated_v2, { function_name: function_name }) do |w| w.max_attempts = 5 w.delay = 5 end rescue Aws::Lambda::Errors::ServiceException => e @logger.error("There was an error updating configurations for #{function_name}:\n #{e.message}") rescue Aws::Waiters::Errors::WaiterFailed => e @logger.error("Failed waiting for #{function_name} to activate:\n #{e.message}") end

案例

下列程式碼範例會示範如何建立可分析客戶評論卡、從其原始語言進行翻譯、判斷對方情緒,以及透過翻譯後的文字產生音訊檔案的應用程式。

SDK for Ruby

此範例應用程式會分析和存儲客戶的意見回饋卡。具體來說,它滿足了紐約市一家虛構飯店的需求。飯店以實體評論卡的形式收到賓客以各種語言撰寫的意見回饋。這些意見回饋透過 Web 用戶端上傳至應用程式。評論卡的影像上傳後,系統會執行下列步驟:

  • 文字內容是使用 Amazon Textract 從影像中擷取。

  • Amazon Comprehend 會決定擷取文字及其用語的情感。

  • 擷取的文字內容會使用 Amazon Translate 翻譯成英文。

  • Amazon Polly 會使用擷取的文字內容合成音訊檔案。

完整的應用程式可透過  AWS CDK 部署。如需原始程式碼和部署的說明,請參閱 GitHub 中的專案。

此範例中使用的服務
  • Amazon Comprehend

  • Lambda

  • Amazon Polly

  • Amazon Textract

  • Amazon Translate

無伺服器範例

下列程式碼範例示範如何實作連線至 RDS 資料庫的 Lambda 函數。該函數會提出簡單的資料庫請求並傳回結果。

SDK for Ruby
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在無伺服器範例儲存庫中設定和執行。

使用 Ruby 連線至 Lambda 函數中的 Amazon RDS 資料庫。

# Ruby code here. require 'aws-sdk-rds' require 'json' require 'mysql2' def lambda_handler(event:, context:) endpoint = ENV['DBEndpoint'] # Add the endpoint without https" port = ENV['Port'] # 3306 user = ENV['DBUser'] region = ENV['DBRegion'] # 'us-east-1' db_name = ENV['DBName'] credentials = Aws::Credentials.new( ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY'], ENV['AWS_SESSION_TOKEN'] ) rds_client = Aws::RDS::AuthTokenGenerator.new( region: region, credentials: credentials ) token = rds_client.auth_token( endpoint: endpoint+ ':' + port, user_name: user, region: region ) begin conn = Mysql2::Client.new( host: endpoint, username: user, password: token, port: port, database: db_name, sslca: '/var/task/global-bundle.pem', sslverify: true, enable_cleartext_plugin: true ) a = 3 b = 2 result = conn.query("SELECT #{a} + #{b} AS sum").first['sum'] puts result conn.close { statusCode: 200, body: result.to_json } rescue => e puts "Database connection failed due to #{e}" end end

下列程式碼範例示範如何實作 Lambda 函數,該函數接收從 Kinesis 串流接收記錄所觸發的事件。此函數會擷取 Kinesis 承載、從 Base64 解碼,並記錄記錄內容。

SDK for Ruby
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在無伺服器範例儲存庫中設定和執行。

使用 Ruby 搭配 Lambda 來使用 Kinesis 事件。

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 require 'aws-sdk' def lambda_handler(event:, context:) event['Records'].each do |record| begin puts "Processed Kinesis Event - EventID: #{record['eventID']}" record_data = get_record_data_async(record['kinesis']) puts "Record Data: #{record_data}" # TODO: Do interesting work based on the new data rescue => err $stderr.puts "An error occurred #{err}" raise err end end puts "Successfully processed #{event['Records'].length} records." end def get_record_data_async(payload) data = Base64.decode64(payload['data']).force_encoding('UTF-8') # Placeholder for actual async work # You can use Ruby's asynchronous programming tools like async/await or fibers here. return data end

下列程式碼範例示範如何實作 Lambda 函數,該函數接收從 DynamoDB 串流接收記錄所觸發的事件。函數會擷取 DynamoDB 承載並記下記錄內容。

SDK for Ruby
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在無伺服器範例儲存庫中設定和執行。

使用 Ruby 搭配 Lambda 來使用 DynamoDB 事件。

def lambda_handler(event:, context:) return 'received empty event' if event['Records'].empty? event['Records'].each do |record| log_dynamodb_record(record) end "Records processed: #{event['Records'].length}" end def log_dynamodb_record(record) puts record['eventID'] puts record['eventName'] puts "DynamoDB Record: #{JSON.generate(record['dynamodb'])}" end

下列程式碼範例示範如何實作 Lambda 函數,該函數接收由從 DocumentDB 變更串流接收記錄所觸發的事件。函數會擷取 DocumentDB 承載並記下記錄內容。

SDK for Ruby
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在無伺服器範例儲存庫中設定和執行。

使用 Ruby 搭配 Lambda 使用 Amazon DocumentDB 事件。

require 'json' def lambda_handler(event:, context:) event['events'].each do |record| log_document_db_event(record) end 'OK' end def log_document_db_event(record) event_data = record['event'] || {} operation_type = event_data['operationType'] || 'Unknown' db = event_data.dig('ns', 'db') || 'Unknown' collection = event_data.dig('ns', 'coll') || 'Unknown' full_document = event_data['fullDocument'] || {} puts "Operation type: #{operation_type}" puts "db: #{db}" puts "collection: #{collection}" puts "Full document: #{JSON.pretty_generate(full_document)}" end

下列程式碼範例示範如何實作 Lambda 函數,該函數接收從 Amazon MSK 叢集接收記錄所觸發的事件。函數會擷取 MSK 承載並記下記錄內容。

SDK for Ruby
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在無伺服器範例儲存庫中設定和執行。

使用 Ruby 搭配 Lambda 來取用 Amazon MSK 事件。

require 'base64' def lambda_handler(event:, context:) # Iterate through keys event['records'].each do |key, records| puts "Key: #{key}" # Iterate through records records.each do |record| puts "Record: #{record}" # Decode base64 msg = Base64.decode64(record['value']) puts "Message: #{msg}" end end end

下列程式碼範例示範如何實作 Lambda 函數,以接收透過將物件上傳至 S3 儲存貯體所觸發的事件。此函數會從事件參數擷取 S3 儲存貯體名稱和物件金鑰,並呼叫 Amazon S3 API 以擷取和記錄物件的內容類型。

SDK for Ruby
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在無伺服器範例儲存庫中設定和執行。

使用 Ruby 搭配 Lambda 來使用 S3 事件。

require 'json' require 'uri' require 'aws-sdk' puts 'Loading function' def lambda_handler(event:, context:) s3 = Aws::S3::Client.new(region: 'region') # Your AWS region # puts "Received event: #{JSON.dump(event)}" # Get the object from the event and show its content type bucket = event['Records'][0]['s3']['bucket']['name'] key = URI.decode_www_form_component(event['Records'][0]['s3']['object']['key'], Encoding::UTF_8) begin response = s3.get_object(bucket: bucket, key: key) puts "CONTENT TYPE: #{response.content_type}" return response.content_type rescue StandardError => e puts e.message puts "Error getting object #{key} from bucket #{bucket}. Make sure they exist and your bucket is in the same region as this function." raise e end end

下列程式碼範例示範如何實作 Lambda 函數,以接收從 SNS 主題接收訊息所觸發的事件。函數會從事件參數擷取訊息,並記錄每一則訊息的內容。

SDK for Ruby
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在無伺服器範例儲存庫中設定和執行。

使用 Ruby 搭配 Lambda 來使用 SNS 事件。

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 def lambda_handler(event:, context:) event['Records'].map { |record| process_message(record) } end def process_message(record) message = record['Sns']['Message'] puts("Processing message: #{message}") rescue StandardError => e puts("Error processing message: #{e}") raise end

下列程式碼範例示範如何實作 Lambda 函數,以接收從 SQS 佇列接收訊息所觸發的事件。函數會從事件參數擷取訊息,並記錄每一則訊息的內容。

SDK for Ruby
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在無伺服器範例儲存庫中設定和執行。

使用 Ruby 搭配 Lambda 來使用 SQS 事件。

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 def lambda_handler(event:, context:) event['Records'].each do |message| process_message(message) end puts "done" end def process_message(message) begin puts "Processed message #{message['body']}" # TODO: Do interesting work based on the new message rescue StandardError => err puts "An error occurred" raise err end end

下列程式碼範例示範如何為接收來自 Kinesis 串流事件的 Lambda 函數實作部分批次回應。此函數會在回應中報告批次項目失敗,指示 Lambda 稍後重試這些訊息。

SDK for Ruby
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在無伺服器範例儲存庫中設定和執行。

使用 Ruby 搭配 Lambda 來報告 Kinesis 批次項目失敗。

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 require 'aws-sdk' def lambda_handler(event:, context:) batch_item_failures = [] event['Records'].each do |record| begin puts "Processed Kinesis Event - EventID: #{record['eventID']}" record_data = get_record_data_async(record['kinesis']) puts "Record Data: #{record_data}" # TODO: Do interesting work based on the new data rescue StandardError => err puts "An error occurred #{err}" # Since we are working with streams, we can return the failed item immediately. # Lambda will immediately begin to retry processing from this failed item onwards. return { batchItemFailures: [{ itemIdentifier: record['kinesis']['sequenceNumber'] }] } end end puts "Successfully processed #{event['Records'].length} records." { batchItemFailures: batch_item_failures } end def get_record_data_async(payload) data = Base64.decode64(payload['data']).force_encoding('utf-8') # Placeholder for actual async work sleep(1) data end

下列程式碼範例示範如何實作 Lambda 函數的部分批次回應,以接收來自 DynamoDB 串流的事件。此函數會在回應中報告批次項目失敗,指示 Lambda 稍後重試這些訊息。

SDK for Ruby
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在無伺服器範例儲存庫中設定和執行。

使用 Ruby 搭配 Lambda 報告 DynamoDB 批次項目失敗。

def lambda_handler(event:, context:) records = event["Records"] cur_record_sequence_number = "" records.each do |record| begin # Process your record cur_record_sequence_number = record["dynamodb"]["SequenceNumber"] rescue StandardError => e # Return failed record's sequence number return {"batchItemFailures" => [{"itemIdentifier" => cur_record_sequence_number}]} end end {"batchItemFailures" => []} end

下列程式碼範例示範如何為從 SQS 佇列接收事件的 Lambda 函數實作部分批次回應。此函數會在回應中報告批次項目失敗,指示 Lambda 稍後重試這些訊息。

SDK for Ruby
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在無伺服器範例儲存庫中設定和執行。

使用 Ruby 搭配 Lambda 報告 SQS 批次項目失敗。

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 require 'json' def lambda_handler(event:, context:) if event batch_item_failures = [] sqs_batch_response = {} event["Records"].each do |record| begin # process message rescue StandardError => e batch_item_failures << {"itemIdentifier" => record['messageId']} end end sqs_batch_response["batchItemFailures"] = batch_item_failures return sqs_batch_response end end