You need to enable JavaScript to run this app. 不使用CloudFormation模板通过API Gateway触发Lambda调用Spring Boot应用的方案
优惠活动
大模型
产品
解决方案
定价
更多

不使用CloudFormation模板通过API Gateway触发Lambda调用Spring Boot应用的方案

手动实现API Gateway触发Lambda调用Spring Boot接口方案

前置准备

  • 已部署好可公网访问/与Lambda同VPC可互通的Spring Boot应用,提前记录要调用接口的请求方法、路径、参数格式要求
  • 已开通对应云服务的API Gateway、Lambda权限,如果Spring Boot部署在VPC内还需要开通Lambda的VPC访问权限

步骤1:创建请求转发Lambda函数

直接在云服务控制台手动创建Lambda,运行环境可根据使用习惯选择,以下为Python 3.9的示例代码,功能是把API Gateway收到的请求原样转发到Spring Boot接口:

import json
import requests

def lambda_handler(event, context):
    # 解析API Gateway传递的请求信息
    http_method = event['requestContext']['http']['method']
    path = event['rawPath']
    query_params = event.get('queryStringParameters', {})
    request_headers = event.get('headers', {})
    request_body = event.get('body', '{}')
    
    # 替换为你自己的Spring Boot应用访问地址
    spring_boot_base_url = "http://你的SpringBoot应用实际访问地址"
    target_url = f"{spring_boot_base_url}{path}"
    
    try:
        # 转发请求到Spring Boot接口
        response = requests.request(
            method=http_method,
            url=target_url,
            params=query_params,
            headers=request_headers,
            json=json.loads(request_body) if request_body else None,
            timeout=15
        )
        # 构造API Gateway要求的返回格式
        return {
            "statusCode": response.status_code,
            "headers": {
                "Content-Type": "application/json"
            },
            "body": response.text
        }
    except Exception as e:
        return {
            "statusCode": 500,
            "body": json.dumps({"error": f"请求转发失败:{str(e)}"})
        }

注意:Python环境的requests包不属于默认内置依赖,需要提前打包成Lambda层上传绑定;如果是用Java写Lambda,用OkHttp或者HttpClient实现相同的转发逻辑即可。另外需要把Lambda的超时时间调整为大于Spring Boot接口的最大响应时间,避免提前中断请求。

步骤2:配置API Gateway触发Lambda

  • 进入API Gateway控制台,选择HTTP API类型(比REST API轻量、成本更低,适配当前转发场景)
  • 点击创建API,集成类型选择Lambda,选中上一步创建的Lambda函数,按照引导完成基础创建
  • 配置路由规则:可以设置{proxy+}通配符路由,匹配所有请求路径和请求方法,所有发往API Gateway的请求都会自动转发到Lambda处理
  • 测试验证:复制API Gateway的调用地址,在后面拼接Spring Boot的接口路径即可访问,比如API Gateway地址是https://xxx.execute-api.xxx.amazonaws.com,要调用Spring Boot的/api/user/list接口,直接请求https://xxx.execute-api.xxx.amazonaws.com/api/user/list即可拿到对应接口的返回结果

常见问题排查

  • 返回502错误优先查看Lambda执行日志,90%以上是Lambda无法访问Spring Boot应用导致,检查网络策略、Spring Boot地址是否正确即可
  • 参数传递异常可以在Lambda中打印完整的event参数,确认API Gateway传递的请求结构是否符合预期,HTTP API默认不需要额外配置参数映射即可拿到完整请求信息
  • 鉴权失败检查是否在转发逻辑中遗漏了Authorization等鉴权头的传递,上述示例代码已经包含请求头转发的逻辑,正常可以直接适配Spring Boot的鉴权逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 10:33:02