如何在对接API Gateway的Spring Cloud Function(Lambda)中获取查询参数
解决方案
方案1:直接绑定API Gateway事件对象(推荐,最直观)
新版本Spring Cloud Function AWS适配器已经原生支持将AWS API Gateway触发的请求自动映射为APIGatewayProxyRequestEvent类型的入参,无需再依赖旧的SpringBootApiGatewayRequestHandler类。
首先确认项目已经引入必要依赖:
<!-- Spring Cloud Function AWS适配器 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-function-adapter-aws</artifactId> </dependency> <!-- AWS Lambda事件定义 --> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-lambda-java-events</artifactId> <version>3.11.1</version> <scope>provided</scope> </dependency>
修改函数定义,将入参类型替换为APIGatewayProxyRequestEvent即可直接获取查询参数、请求头、请求体等所有API Gateway传递的信息:
@SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean public Function<APIGatewayProxyRequestEvent, String> uppercase() { return event -> { // 获取所有查询参数 Map<String, String> queryParams = event.getQueryStringParameters(); // 示例:获取名为id的查询参数 String id = queryParams != null ? queryParams.get("id") : "无参数"; // 原有逻辑:获取请求体转大写 String body = event.getBody(); return body != null ? body.toUpperCase() : "无请求体, 传入的id参数为: " + id; }; } }
最后配置Lambda的处理程序为org.springframework.cloud.function.adapter.aws.FunctionInvoker即可,不需要自定义Handler类。
方案2:使用通用Message入参(兼容多触发场景)
如果你的函数需要同时支持API Gateway、其他Lambda触发方式或者本地调用,可以使用Message作为入参,从Header中提取API Gateway事件对象:
@Bean public Function<Message<String>, String> uppercase() { return message -> { // 从Header中获取API Gateway事件对象 APIGatewayProxyRequestEvent event = message.getHeaders().get("aws_request_event", APIGatewayProxyRequestEvent.class); Map<String, String> queryParams = event != null ? event.getQueryStringParameters() : null; String id = queryParams != null ? queryParams.get("id") : "无参数"; // 获取请求体 String body = message.getPayload(); return body != null ? body.toUpperCase() : "无请求体, 传入的id参数为: " + id; }; }
内容的提问来源于stack exchange,提问作者user1555190
相关产品推荐
相关产品推荐

