如何用AWS Lambda托管Spring Boot API?控制器调用问题咨询
将Spring Boot控制器部署到AWS Lambda的实现方案
核心思路
无需手动实现RequestStreamHandler,借助Spring生态与AWS适配工具,让Lambda请求自动转发到你的控制器,原有控制器代码无需修改。
具体步骤
1. 添加必要依赖
如果是Maven项目,在pom.xml中添加以下依赖:
<!-- Spring Boot Web核心 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <!-- 排除内嵌Tomcat,Lambda无需容器 --> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> <!-- AWS Lambda Spring Boot适配器 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-function-adapter-aws</artifactId> <version>3.2.7</version> </dependency> <!-- AWS Lambda事件模型 --> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-lambda-java-events</artifactId> <version>3.11.1</version> </dependency> <!-- AWS Lambda核心库 --> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-lambda-java-core</artifactId> <version>1.2.21</version> <scope>provided</scope> </dependency>
2. 编写Lambda入口类
创建入口类,继承SpringBootRequestHandler,指定输入输出事件类型(适配API Gateway触发场景):
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.function.adapter.aws.SpringBootRequestHandler; @SpringBootApplication public class LambdaControllerHandler extends SpringBootRequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> { public static void main(String[] args) { SpringApplication.run(LambdaControllerHandler.class, args); } }
3. 保留原有Hello World控制器
无需修改你的控制器代码,示例如下:
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @GetMapping("/hello") public String helloWorld() { return "Hello World"; } }
4. 打包部署
- 执行Maven打包:
mvn clean package,生成可执行JAR文件 - 登录AWS控制台创建Lambda函数,选择上传JAR包的方式,上传打包好的文件
- 在Lambda配置中设置处理程序为入口类全路径(如
com.example.LambdaControllerHandler,替换为你的实际包名+类名) - 配置API Gateway触发器:选择HTTP API或REST API,关联Lambda函数,设置路径为
/hello、请求方法为GET
5. 测试调用
- 通过API Gateway生成的URL访问
https://<api-id>.execute-api.<region>.amazonaws.com/prod/hello,即可得到"Hello World"响应 - 也可在Lambda控制台测试功能中,构造如下事件测试:
{ "httpMethod": "GET", "path": "/hello" }
关键说明
- 适配器会自动将Lambda事件转换为Spring MVC可识别的请求,转发到对应控制器方法
- 若无需HTTP访问,可直接通过Lambda控制台/SDK调用,但需构造符合适配器要求的输入事件
- 排除内嵌容器能有效减小包体积,降低Lambda资源消耗
内容的提问来源于stack exchange,提问作者user12501158
相关产品推荐
相关产品推荐

