
关于
构建生产级 AWS 无服务器应用的专业技能。
name: aws-serverless description: 专门用于在AWS上构建生产就绪的无服务器应用的技能。涵盖Lambda函数、API Gateway、DynamoDB、SQS/SNS事件驱动模式、SAM/CDK部署和冷启动优化。 risk: unknown source: vibeship-spawner-skills (Apache 2.0) date_added: 2026-02-27
AWS 无服务器
专门用于在AWS上构建生产就绪的无服务器应用的技能。涵盖Lambda函数、API Gateway、DynamoDB、SQS/SNS事件驱动模式、SAM/CDK部署和冷启动优化。
原则
- 合理配置内存和超时时间(先测量再优化)
- 为延迟敏感的工作负载最小化冷启动
- 对Java/.NET函数使用SnapStart
- 简单用例优先使用HTTP API而非REST API
- 使用DLQ和重试机制为故障而设计
- 保持部署包体积小
- 使用环境变量进行配置
- 实现带关联ID的结构化日志
模式
Lambda 处理器模式
带错误处理的正确Lambda函数结构
何时使用:任何Lambda函数实现、API处理器、事件处理器、定时任务
// Node.js Lambda Handler
// handler.js
// Initialize outside handler (reused across invocations)
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb');
const { DynamoDBDocumentClient, GetCommand } = require('@aws-sdk/lib-dynamodb');
const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);
// Handler function
exports.handler = async (event, context) => {
// Optional: Don't wait for event loop to clear (Node.js)
context.callbackWaitsForEmptyEventLoop = false;
try {
// Parse input based on event source
const body = typeof event.body === 'string'
? JSON.parse(event.body)
: event.body;
// Business logic
const result = await processRequest(body);
// Return API Gateway compatible response
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify(result)
};
} catch (error) {
console.error('Error:', JSON.stringify({
error: error.message,
stack: error.stack,
requestId: context.awsRequestId
}));
return {
statusCode: error.statusCode || 500,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
error: error.message || 'Internal server error'
})
};
}
};
async function processRequest(data) {
// Your business logic here
const result = await docClient.send(new GetCommand({
TableName: process.env.TABLE_NAME,
Key: { id: data.id }
}));
return result.Item;
}
# Python Lambda Handler
# handler.py
import json
import os
import logging
import boto3
from botocore.exceptions import ClientError
# Initialize outside handler (reused across invocations)
logger = logging.getLogger()
logger.setLevel(logging.INFO)
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(os.environ['TABLE_NAME'])
def handler(event, context):
try:
# Parse input
body = json.loads(event.get('body', '{}')) if isinstance(event.get('body'), str) else event.get('body', {})
# Business logic
result = process_request(body)
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
'body': json.dumps(result)
}
except ClientError as e:
logger.error(f"DynamoDB error: {e.response['Error']['Message']}")
return error_response(500, 'Database error')
except json.JSONDecodeError:
return error_response(400, 'Invalid JSON')
except Exception as e:
logger.error(f"Unexpected error: {str(e)}", exc_info=True)
return error_response(500, 'Internal server error')
def process_request(data):
response = table.get_item(Key={'id': data['id']})
return response.get('Item')
def error_response(status_code, message):
return {
'statusCode': status_code,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps({'error': message})
}
最佳实践
- 在处理器外部初始化客户端(在热启动调用间复用)
- 始终返回正确的API Gateway响应格式
- 使用结构化JSON日志以便CloudWatch Insights查询
- 在错误日志中包含请求ID以便追踪
API Gateway 集成模式
REST API和HTTP API与Lambda的集成
何时使用:构建Lambda支持的REST API、需要函数的HTTP端点
# template.yaml (SAM)
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Globals:
Function:
Runtime: nodejs20.x
Timeout: 30
MemorySize: 256
Environment:
Variables:
TABLE_NAME: !Ref ItemsTable
Resources:
# HTTP API (recommended for simple cases)
HttpApi:
Type: AWS::Serverless::HttpApi
Properties:
StageName: prod
CorsConfiguration:
AllowOrigins:
- "*"
AllowMethods:
- GET
- POST
- PUT
- DELETE
# Lambda function
ItemsFunction:
Type: AWS::Serverless::Function
Properties:
Handler: handler.handler
Events:
GetItems:
Type: HttpApi
Properties:
ApiId: !Ref HttpApi
Path: /items
Method: GET
CreateItem:
Type: HttpApi
Properties:
ApiId: !Ref HttpApi
Path: /items
Method: POST
# DynamoDB table
ItemsTable:
Type: AWS::DynamoDB::Table
Properties:
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: id
AttributeType: S
KeySchema:
- AttributeName: id
KeyType: HASH
兼容工具
Claude CodeCursor
标签
后端开发
