You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AWS CDK中配置API Gateway方法级限流(无需控制台手动调整)?

AWS API Gateway方法级限流的AWS CDK实现方法

可以通过AWS CDK实现REST API方法级限流的阶段覆盖配置,无需手动操作控制台,完全替代你之前在控制台阶段设置中用“override”配置限流的操作。

核心实现逻辑

在CDK中,你可以先定义API的全局默认限流规则,再通过部署阶段(Stage)的throttle属性,针对特定API方法设置专属的限流参数,以此覆盖全局规则,效果和控制台手动配置完全一致。

TypeScript代码示例

import { RestApi, LambdaIntegration, Deployment, Stage } from 'aws-cdk-lib/aws-apigateway';
import { Function, Runtime, Code } from 'aws-cdk-lib/aws-lambda';
import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';

export class ApiThrottleStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    // 创建后端Lambda函数
    const backendFn = new Function(this, 'BackendFn', {
      runtime: Runtime.NODEJS_20_X,
      handler: 'index.handler',
      code: Code.fromInline(`
        exports.handler = async (event) => {
          return {
            statusCode: 200,
            body: JSON.stringify({ message: 'Hello World' })
          };
        };
      `)
    });

    // 创建REST API,配置全局默认限流
    const api = new RestApi(this, 'MyApi', {
      restApiName: 'My Throttled API',
      defaultMethodOptions: {
        throttling: {
          rateLimit: 100,
          burstLimit: 20
        }
      }
    });

    // 添加API资源与方法
    const usersResource = api.root.addResource('users');
    const getUsersMethod = usersResource.addMethod('GET', new LambdaIntegration(backendFn));
    const postUsersMethod = usersResource.addMethod('POST', new LambdaIntegration(backendFn));

    // 创建部署与阶段,配置方法级限流覆盖
    const deployment = new Deployment(this, 'ApiDeployment', { api });
    new Stage(this, 'ProdStage', {
      deployment,
      stageName: 'prod',
      throttle: {
        // 针对GET /users方法设置专属限流
        [`${getUsersMethod.resource.path}/${getUsersMethod.httpMethod}`]: {
          rateLimit: 500,
          burstLimit: 100
        },
        // 针对POST /users方法设置专属限流
        [`${postUsersMethod.resource.path}/${postUsersMethod.httpMethod}`]: {
          rateLimit: 100,
          burstLimit: 30
        }
      }
    });
  }
}

Python代码示例

from aws_cdk import (
    Stack,
    aws_apigateway as apigateway,
    aws_lambda as _lambda,
)
from constructs import Construct

class ApiThrottleStack(Stack):
    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # 创建后端Lambda函数
        backend_fn = _lambda.Function(
            self, "BackendFn",
            runtime=_lambda.Runtime.PYTHON_3_11,
            handler="index.handler",
            code=_lambda.Code.from_inline("""
def handler(event, context):
    return {
        'statusCode': 200,
        'body': '{"message": "Hello World"}'
    }
""")
        )

        # 创建REST API,配置全局默认限流
        api = apigateway.RestApi(
            self, "MyApi",
            rest_api_name="My Throttled API",
            default_method_options={
                "throttling": {
                    "rate_limit": 100,
                    "burst_limit": 20
                }
            }
        )

        # 添加API资源与方法
        users_resource = api.root.add_resource("users")
        get_users_method = users_resource.add_method("GET", apigateway.LambdaIntegration(backend_fn))
        post_users_method = users_resource.add_method("POST", apigateway.LambdaIntegration(backend_fn))

        # 创建部署与阶段,配置方法级限流覆盖
        deployment = apigateway.Deployment(self, "ApiDeployment", api=api)
        apigateway.Stage(
            self, "ProdStage",
            deployment=deployment,
            stage_name="prod",
            throttle={
                f"{get_users_method.resource.path}/{get_users_method.http_method}": {
                    "rate_limit": 500,
                    "burst_limit": 100
                },
                f"{post_users_method.resource.path}/{post_users_method.http_method}": {
                    "rate_limit": 100,
                    "burst_limit": 30
                }
            }
        )

关键说明

  • throttle参数的键格式为[资源路径]/[HTTP方法],用来精准定位需要覆盖限流的API方法
  • 方法级配置的rateLimit(每秒请求数)和burstLimit(突发请求数)会直接覆盖全局默认规则
  • 部署CDK栈后,限流规则会自动生效,无需再手动操作AWS控制台

内容的提问来源于stack exchange,提问作者Nigel Sheridan-Smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 19:28:16