AWS Serverless架构实践指南

深入理解AWS Serverless架构设计与实现方案

AWS Serverless架构详解

本文将深入介绍AWS Serverless架构的设计原则和最佳实践,帮助你构建可靠的无服务器应用。

Lambda函数

  1. 基础配置
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# serverless.yml
service: my-service

provider:
  name: aws
  runtime: nodejs14.x
  region: us-east-1

functions:
  hello:
    handler: handler.hello
    events:
      - http:
          path: hello
          method: get
  1. 函数实现
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// handler.js
exports.hello = async (event) => {
    return {
        statusCode: 200,
        body: JSON.stringify({
            message: 'Hello from Lambda!'
        })
    };
};

// 处理S3事件
exports.processS3Event = async (event) => {
    const record = event.Records[0];
    const bucket = record.s3.bucket.name;
    const key = record.s3.object.key;
    // 处理S3文件
};

API Gateway

  1. REST API配置
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
resources:
  Resources:
    ApiGatewayRestApi:
      Type: AWS::ApiGateway::RestApi
      Properties:
        Name: my-api
        
    ApiGatewayResource:
      Type: AWS::ApiGateway::Resource
      Properties:
        ParentId: !GetAtt ApiGatewayRestApi.RootResourceId
        PathPart: items
        RestApiId: !Ref ApiGatewayRestApi
  1. 集成Lambda
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
functions:
  getItems:
    handler: handler.getItems
    events:
      - http:
          path: items
          method: get
          cors: true
          authorizer:
            name: customAuthorizer
            type: token

DynamoDB集成

  1. 表定义
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
resources:
  Resources:
    UsersTable:
      Type: AWS::DynamoDB::Table
      Properties:
        TableName: users
        AttributeDefinitions:
          - AttributeName: id
            AttributeType: S
        KeySchema:
          - AttributeName: id
            KeyType: HASH
        BillingMode: PAY_PER_REQUEST
  1. CRUD操作
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB.DocumentClient();

// 创建用户
async function createUser(user) {
    const params = {
        TableName: 'users',
        Item: {
            id: user.id,
            name: user.name,
            email: user.email
        }
    };
    
    await dynamodb.put(params).promise();
}

// 查询用户
async function getUser(id) {
    const params = {
        TableName: 'users',
        Key: { id }
    };
    
    const result = await dynamodb.get(params).promise();
    return result.Item;
}

S3集成

  1. 存储桶配置
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
resources:
  Resources:
    UploadBucket:
      Type: AWS::S3::Bucket
      Properties:
        BucketName: my-uploads
        CorsConfiguration:
          CorsRules:
            - AllowedHeaders: ['*']
              AllowedMethods: [GET, PUT, POST, DELETE]
              AllowedOrigins: ['*']
  1. 文件处理
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
const AWS = require('aws-sdk');
const s3 = new AWS.S3();

// 上传文件
async function uploadFile(file) {
    const params = {
        Bucket: 'my-uploads',
        Key: `${Date.now()}-${file.name}`,
        Body: file.content,
        ContentType: file.type
    };
    
    await s3.putObject(params).promise();
}

// 生成预签名URL
async function getSignedUrl(key) {
    const params = {
        Bucket: 'my-uploads',
        Key: key,
        Expires: 3600
    };
    
    return s3.getSignedUrlPromise('getObject', params);
}

SQS集成

  1. 队列配置
1
2
3
4
5
6
7
resources:
  Resources:
    ProcessingQueue:
      Type: AWS::SQS::Queue
      Properties:
        QueueName: processing-queue
        VisibilityTimeout: 30
  1. 消息处理
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// 发送消息
async function sendMessage(data) {
    const sqs = new AWS.SQS();
    const params = {
        QueueUrl: process.env.QUEUE_URL,
        MessageBody: JSON.stringify(data)
    };
    
    await sqs.sendMessage(params).promise();
}

// 处理消息
exports.processMessage = async (event) => {
    for (const record of event.Records) {
        const body = JSON.parse(record.body);
        // 处理消息
    }
};

CloudWatch监控

  1. 日志配置
1
2
3
4
5
6
7
8
functions:
  hello:
    handler: handler.hello
    events:
      - http:
          path: hello
          method: get
    logRetentionInDays: 14
  1. 指标监控
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
const AWS = require('aws-sdk');
const cloudwatch = new AWS.CloudWatch();

async function recordMetric(name, value) {
    const params = {
        MetricData: [{
            MetricName: name,
            Value: value,
            Unit: 'Count',
            Timestamp: new Date()
        }],
        Namespace: 'MyApplication'
    };
    
    await cloudwatch.putMetricData(params).promise();
}

认证授权

  1. Cognito配置
1
2
3
4
5
6
7
8
resources:
  Resources:
    UserPool:
      Type: AWS::Cognito::UserPool
      Properties:
        UserPoolName: my-user-pool
        AutoVerifiedAttributes:
          - email
  1. JWT验证
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const jwt = require('jsonwebtoken');

exports.authorizer = async (event) => {
    const token = event.authorizationToken;
    try {
        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        return generatePolicy(decoded.sub, 'Allow', event.methodArn);
    } catch (err) {
        return generatePolicy('user', 'Deny', event.methodArn);
    }
};

最佳实践

  1. 架构建议

    • 使用无状态设计
    • 实现幂等性
    • 合理设置超时
    • 使用死信队列
  2. 开发建议

    • 本地测试
    • 环境变量管理
    • 错误处理
    • 性能优化

掌握这些AWS Serverless架构设计原则,将帮助你构建可靠、高效的无服务器应用。

使用绝夜之城强力驱动