Lambda 模式

事件源

事件源触发类型说明
API Gateway / ALB同步HTTP 请求/响应
S3异步对象创建/删除事件
DynamoDB Streams轮询批量处理流记录
SQS轮询长轮询,批量 1-10000
SNS异步扇出模式
EventBridge异步定时或事件驱动

函数配置

# 创建 Lambda 函数 aws lambda create-function \ --function-name my-function \ --runtime python3.12 \ --role arn:aws:iam::123456789012:role/lambda-role \ --handler app.handler \ --zip-file fileb://function.zip \ --memory-size 512 \ --timeout 30 \ --environment Variables="{DB_HOST=db.example.com}" # 更新函数代码 aws lambda update-function-code \ --function-name my-function \ --zip-file fileb://function.zip # 调用函数 aws lambda invoke \ --function-name my-function \ --payload '{"key": "value"}' \ --cli-binary-format raw-in-base64-out \ response.json

层(Layers)

# 发布层 zip -r layer.zip python/ aws lambda publish-layer-version \ --layer-name my-dependencies \ --zip-file fileb://layer.zip \ --compatible-runtimes python3.12 # 为函数挂载层 aws lambda update-function-configuration \ --function-name my-function \ --layers arn:aws:lambda:us-east-1:123456789012:layer:my-dependencies:3 # 层目录结构 # python/lib/python3.12/site-packages/ # nodejs/node_modules/

VPC 配置

# 将 Lambda 挂载到 VPC aws lambda update-function-configuration \ --function-name my-function \ --vpc-config SubnetIds=subnet-abc123,SecurityGroupIds=sg-789012 # 注意:VPC 内的 Lambda 访问互联网需要 NAT 网关

冷启动优化

# 预置并发(预热实例) aws lambda put-provisioned-concurrency-config \ --function-name my-function \ --qualifier LIVE \ --provisioned-concurrent-executions 10 # 冷启动优化最佳实践: # 1. 保持部署包小(< 10 MB) # 2. 优先选择编译型运行时(Go、.NET) # 3. 在 handler 外部初始化 DB 连接 # 4. Java 使用 Lambda SnapStart # 5. 避免加载未使用的依赖

SAM 模板

AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Resources: ApiFunction: Type: AWS::Serverless::Function Properties: Handler: app.handler Runtime: python3.12 CodeUri: src/ Events: ApiEvent: Type: Api Properties: Path: /items Method: get # 部署 # sam build && sam deploy --guided