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

如何通过Serverless框架/插件实现API Gateway无Lambda集成Kinesis流

实现无Lambda的API Gateway到Kinesis流的Serverless框架集成

当然可以实现这种无Lambda的直接集成!我之前帮别人配置过类似的场景,用Serverless框架完全能做到,核心是借助CloudFormation的资源定义来直接配置API Gateway和Kinesis的集成,不用绕Lambda。下面给你具体的实现方案和配置示例:

核心原理

API Gateway支持AWS服务直接集成,不需要通过Lambda作为中间层。我们可以直接把API的请求映射到Kinesis的PutRecord(或PutRecords)动作,通过请求模板转换请求格式,同时给API Gateway配置足够的IAM权限来调用Kinesis。

Serverless框架配置示例

你可以直接在serverless.yml里定义所需的CloudFormation资源,实现端到端的配置。这里是一个完整的示例:

service: api-kinesis-direct-integration

provider:
  name: aws
  runtime: nodejs18.x # 框架要求填写runtime,但实际不会用到Lambda
  region: us-east-1
  environment:
    KINESIS_STREAM_NAME: MyDirectIntegrationStream

resources:
  Resources:
    # 1. 定义Kinesis流(如果已经手动创建过,可删除这部分)
    MyKinesisStream:
      Type: AWS::Kinesis::Stream
      Properties:
        Name: ${self:provider.environment.KINESIS_STREAM_NAME}
        ShardCount: 1

    # 2. 创建API Gateway实例
    DirectApi:
      Type: AWS::ApiGateway::RestApi
      Properties:
        Name: ApiToKinesisDirect
        Description: REST API directly integrated with Kinesis Stream

    # 3. 定义API路径(比如/post-event)
    ApiEventResource:
      Type: AWS::ApiGateway::Resource
      Properties:
        ParentId: !GetAtt DirectApi.RootResourceId
        PathPart: post-event
        RestApiId: !Ref DirectApi

    # 4. 配置POST方法,直接集成到Kinesis
    ApiPostMethod:
      Type: AWS::ApiGateway::Method
      Properties:
        AuthorizationType: NONE # 生产环境建议替换为IAM/API Key认证
        HttpMethod: POST
        ResourceId: !Ref ApiEventResource
        RestApiId: !Ref DirectApi
        Integration:
          Type: AWS
          IntegrationHttpMethod: POST
          # 指向Kinesis的PutRecord动作
          Uri: !Sub 'arn:aws:apigateway:${self:provider.region}:kinesis:action/PutRecord'
          # 给API Gateway分配调用Kinesis的IAM角色
          Credentials: !GetAtt ApiGatewayKinesisRole.Arn
          # 请求模板:把API请求转换为Kinesis需要的格式
          RequestTemplates:
            application/json: |
              {
                "StreamName": "${self:provider.environment.KINESIS_STREAM_NAME}",
                "Data": "$util.base64Encode($input.body)",
                "PartitionKey": "$input.path('$.eventId')" # 从请求body里取分区键,可自定义
              }
          # 集成响应配置
          IntegrationResponses:
            - StatusCode: 200
              ResponseTemplates:
                application/json: '{"status": "success", "message": "Event sent to Kinesis"}'
            - StatusCode: 400
              SelectionPattern: "4\\d{2}"
              ResponseTemplates:
                application/json: '{"status": "error", "message": "Invalid request"}'
        # 方法响应配置
        MethodResponses:
          - StatusCode: 200
          - StatusCode: 400

    # 5. 创建API Gateway调用Kinesis所需的IAM角色
    ApiGatewayKinesisRole:
      Type: AWS::IAM::Role
      Properties:
        AssumeRolePolicyDocument:
          Version: '2012-10-17'
          Statement:
            - Effect: Allow
              Principal:
                Service: apigateway.amazonaws.com
              Action: sts:AssumeRole
        Policies:
          - PolicyName: ApiGatewayKinesisAccessPolicy
            PolicyDocument:
              Version: '2012-10-17'
              Statement:
                - Effect: Allow
                  Action: kinesis:PutRecord
                  Resource: !GetAtt MyKinesisStream.Arn

    # 6. 部署API Gateway到prod环境
    ApiDeployment:
      Type: AWS::ApiGateway::Deployment
      DependsOn: ApiPostMethod
      Properties:
        RestApiId: !Ref DirectApi
        StageName: prod

  # 输出API端点,方便测试
  Outputs:
    ApiEndpoint:
      Value: !Sub 'https://${DirectApi}.execute-api.${self:provider.region}.amazonaws.com/prod/post-event'

关键配置说明

  • 请求模板:Kinesis要求Data字段必须是base64编码的内容,所以用$util.base64Encode($input.body)把请求body转成符合要求的格式;PartitionKey可以从请求的任意字段提取,或者设为固定值(但固定值可能导致热点分片,生产环境建议用业务相关的唯一标识)。
  • IAM角色:必须给API Gateway分配能调用KinesisPutRecord的权限,否则集成会失败。
  • 认证方式:示例里用了NONE(公开访问),实际生产环境建议换成AWS_IAM(让调用者用IAM凭证认证)或者API_KEY,避免未授权的请求。

部署与测试

  1. 把上述配置保存为serverless.yml
  2. 运行serverless deploy,等待资源创建完成
  3. 从输出里拿到ApiEndpoint,用curl或Postman发送POST请求测试:
curl -X POST https://your-api-id.execute-api.us-east-1.amazonaws.com/prod/post-event \
  -H "Content-Type: application/json" \
  -d '{"eventId": "12345", "data": "test event from API"}'

额外注意点

  • 如果你的Kinesis流已经通过控制台创建好了,直接删除配置里的MyKinesisStream部分,把Resource里的ARN替换成你现有流的ARN即可。
  • 如果需要批量发送事件,可以把集成指向Kinesis的PutRecords动作,同时调整请求模板来适配批量数据格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:46:51