如何通过OpenAPI Spec覆盖API Gateway默认的方法缓存设置?
解决方案
1. 通过OpenAPI Spec实现方法级缓存按需启用
AWS API Gateway支持通过OpenAPI扩展字段x-amazon-apigateway-method-settings,在方法级别覆盖Stage的缓存配置,实现「默认禁用、指定方法启用」的按需模式:
- 保持Stage级别已启用缓存的配置(你已完成此操作);
- 在需要开启缓存的API方法的
operation节点下,添加x-amazon-apigateway-method-settings扩展,设置cachingEnabled: true,同时可按需指定cacheTtlInSeconds(缓存过期时间); - 未配置该扩展的方法,默认继承Stage的「缓存禁用」行为(Stage开启缓存后,方法默认不启用缓存,需显式配置开启)。
2. 配置完整路径作为缓存键
要将完整路径(而非仅路径参数)作为缓存键,可使用API Gateway的上下文变量context.request.path——该变量会返回完整的请求路径(包含静态路径段和路径参数的实际值):
- 在
x-amazon-apigateway-method-settings的cacheKeyParameters数组中添加"context.request.path"; - 该配置对两种路径场景均生效:
- 静态路径(如
/a/b):缓存键为完整路径/a/b; - 带参数路径(如
/a/b/{item_id}):缓存键为包含参数值的完整路径(如/a/b/123),避免不同参数值的请求共用缓存。
- 静态路径(如
完整OpenAPI Spec示例
openapi: 3.0.1 info: title: 示例API version: 1.0.0 paths: /a/b: get: summary: 静态路径端点 x-amazon-apigateway-method-settings: cachingEnabled: true cacheTtlInSeconds: 300 cacheKeyParameters: - "context.request.path" responses: '200': description: 成功响应 /a/b/{item_id}: get: summary: 带路径参数的端点 parameters: - name: item_id in: path required: true schema: type: string x-amazon-apigateway-method-settings: cachingEnabled: true cacheTtlInSeconds: 300 cacheKeyParameters: - "context.request.path" responses: '200': description: 成功响应 x-amazon-apigateway-stage: cachingEnabled: true cacheClusterSize: '0.5' # 根据实际需求调整缓存集群大小
补充说明
- 之前导出的OpenAPI Spec未包含缓存相关字段,是因为只有当方法级缓存配置被显式设置后,导出的Spec才会包含
x-amazon-apigateway-method-settings扩展,默认情况下该字段不会自动生成,需手动添加; - 若需要额外添加其他缓存键参数(如查询参数),可在
cacheKeyParameters数组中追加,例如"method.request.querystring.param_name"。
内容的提问来源于stack exchange,提问作者Arko Chakraborti
相关产品推荐
相关产品推荐

