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

如何通过OpenApi YAML为AWS APIGateway指定单方法启用缓存

配置方案

你可以通过AWS API Gateway专属的OpenAPI扩展字段x-amazon-apigateway-method-settings实现需求,不需要手动修改其他端点配置,步骤如下:

1. 新增全局默认关闭GET缓存配置

在你的OpenAPI YAML的根层级(和paths节点平级)新增如下配置,批量关闭所有GET端点的缓存,覆盖stage级的默认开启规则:

# 与paths同级的根节点配置
x-amazon-apigateway-method-settings:
  - resource_path: "/*"
    http_method: "GET"
    settings:
      caching_enabled: false
      cache_ttl_in_seconds: 0

2. 单独为目标端点开启缓存

在你提供的/users/{userId}的GET方法配置中,新增方法级的缓存配置,优先级会高于全局规则,示例如下(标注---新增配置开始---和---新增配置结束---的部分为新增内容):

/users/{userId}:
  get:
    description: Get user details
    parameters:
      - description: Valid user id
        in: path
        name: userId
        required: true
        schema:
          type: string
    responses:
      '200':
        content: {}
        description: Success
        headers:
          Access-Control-Allow-Origin:
            schema:
              type: string
      '400':
        content: {}
        description: Invalid user id
    security:
      - NodeJsAuth: []
    summary: Get User Id Details
    tags:
      - User
    # ---新增配置开始---
    x-amazon-apigateway-method-settings:
      settings:
        caching_enabled: true
        cache_ttl_in_seconds: 300 # 可自定义缓存时长,单位为秒
        cache_key_parameters:
          - method.request.path.userId # 必须将userId加入缓存键,避免不同用户命中同一份缓存
    # ---新增配置结束---
    x-amazon-apigateway-integration:
      connectionId: ${stageVariables.vpcLinkId}
      connectionType: VPC_LINK
      httpMethod: GET
      passthroughBehavior: when_no_match
      requestParameters:
        integration.request.path.userId: method.request.path.userId
      responses:
        default:
          responseParameters:
            method.response.header.Access-Control-Allow-Origin: '''*'''
          statusCode: '200'
      type: http_proxy
      uri: '#{EksElbUri}#/user/{userId}'

规则说明

  • API Gateway的配置优先级为:方法级 > 全局OpenAPI配置 > stage级控制台配置,因此上述配置生效后,仅目标GET端点会开启缓存,其余所有GET端点缓存默认关闭
  • 若你需要基于其他参数(比如请求头、查询参数)做缓存隔离,可在cache_key_parameters中添加对应参数的取值路径即可

内容的提问来源于stack exchange,提问作者Sivvie Lim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 18:06:00