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

如何通过AWS CDK实现仅缓存无查询参数的API Gateway请求

如何通过AWS CDK实现仅缓存无查询参数的API Gateway请求?

要实现仅缓存不带search查询参数的/v1/services请求,你可以通过API Gateway的响应头控制结合CDK配置来实现——核心思路是让带search参数的请求返回不缓存的响应头,而不带参数的请求返回允许缓存的响应头,同时保持全局缓存启用。

具体步骤和CDK代码示例如下:

1. 配置方法缓存及动态响应头

保持原有缓存基础配置,添加响应头映射逻辑来动态控制缓存行为:

import * as apigateway from 'aws-cdk-lib/aws-apigateway';
import { Duration } from 'aws-cdk-lib';

// 假设你已创建API实例和后端集成(比如Lambda集成)
const api = new apigateway.RestApi(this, 'ServicesApi');
const servicesResource = api.root.addResource('v1').addResource('services');
const lambdaIntegration = new apigateway.LambdaIntegration(yourLambdaFunction);

// 添加GET方法并配置缓存规则
servicesResource.addMethod('GET', lambdaIntegration, {
  methodOptions: {
    'GET': {
      cachingEnabled: true,
      cacheDataEncrypted: true,
      cacheTtl: Duration.minutes(3),
      cacheKeyParameters: [], // 确保缓存键仅包含路径和HTTP方法,不包含查询参数
      // 配置响应头及动态模板
      methodResponses: [
        {
          statusCode: '200',
          // 声明要自定义的响应头
          responseParameters: {
            'method.response.header.Cache-Control': true,
          },
          // 通过VTL模板判断请求参数并设置缓存控制头
          responseTemplates: {
            'application/json': `
#set($hasSearch = $input.params('search') != '')
#set($cacheHeader = $hasSearch ? 'no-cache, no-store, must-revalidate' : 'max-age=180')
$input.json('$')
#set($context.responseOverride.header.Cache-Control = $cacheHeader)
            `,
          },
        },
      ],
    },
  },
});

2. 逻辑说明

  • 基础缓存配置:全局开启方法缓存,同时配置加密规则和默认TTL。
  • 动态缓存控制:通过Velocity模板语言(VTL)判断请求是否包含search参数:
    • 若存在search参数,返回Cache-Control: no-cache, no-store, must-revalidate,API Gateway会跳过该响应的缓存。
    • 若不存在search参数,返回Cache-Control: max-age=180(与配置的3分钟TTL对应),API Gateway会缓存该响应。
  • 缓存键优化:cacheKeyParameters: []确保缓存键仅由路径和HTTP方法组成,避免因不同查询参数生成冗余缓存条目。

额外注意事项

  • 上述配置适用于AWS API Gateway REST API;若使用HTTP API,需结合CachePolicy配置路由级缓存,但HTTP API的缓存条件支持有限,推荐使用REST API方案。
  • 确保后端集成(如Lambda)不会覆盖Cache-Control响应头,否则会干扰API Gateway的缓存逻辑。

内容的提问来源于stack exchange,提问作者Davide Bracaglia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 18:31:02