配置Spring Boot Lambda以无缝处理EventBridge触发并实现保活
问题描述
我是AWS新手,需求是通过定时触发Spring Boot Lambda实现保活。已配置EventBridge规则触发Lambda,但出现报错:
"com.amazonaws.serverless.exceptions.InvalidRequestEventException: The incoming event is not a valid request from Amazon API Gateway or an Application Load Balancer"
该Lambda暴露的HTTP端点可通过Postman和API网关正常访问,请问需做哪些修改,使Lambda既能打印“Lambda Triggered”实现保活,又能无缝处理定时触发事件,同时不影响原有HTTP功能?
现有LambdaHandler代码
public class LambdaHandler implements RequestStreamHandler { private static SpringBootLambdaContainerHandler<AwsProxyRequest, AwsProxyResponse> handler; static { try { handler = SpringBootLambdaContainerHandler.getAwsProxyHandler(Application.class); // If you are using HTTP APIs with the version 2.0 of the proxy model, use the getHttpApiV2ProxyHandler // method: handler = SpringBootLambdaContainerHandler.getHttpApiV2ProxyHandler(Application.class); } catch (ContainerInitializationException e) { // if we fail here. We re-throw the exception to force another cold start e.printStackTrace(); throw new RuntimeException("Could not initialize Spring Boot application", e); } } @Override public void handleRequest(InputStream input, OutputStream output, Context context) throws IOException { handler.proxyStream(input, output, context); } }
现有SAM中的EventBridge规则配置
MyEventBridgeRule: Type: AWS::Events::Rule Properties: EventPattern: source: - "aws.events" ScheduleExpression: "cron(0/5 * * * ? *)" # Example schedule expression State: ENABLED Targets: - Arn: !GetAtt ProductInfoSamFunction.Arn Id: "MyLambdaBridgeTarget"
解决方案
问题根源是当前Lambda Handler仅处理API Gateway/ALB的代理请求,无法识别EventBridge的定时事件格式。要兼容两种触发方式,需修改Handler逻辑,先判断事件类型再分别处理:
步骤1:修改LambdaHandler.java
在handleRequest方法中,先读取输入流内容,判断是否为EventBridge事件,再决定是交给Spring Boot容器处理还是直接执行保活逻辑:
import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestStreamHandler; import com.amazonaws.serverless.proxy.model.AwsProxyRequest; import com.amazonaws.serverless.proxy.model.AwsProxyResponse; import com.amazonaws.serverless.proxy.spring.SpringBootLambdaContainerHandler; import com.amazonaws.serverless.exceptions.ContainerInitializationException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.*; import java.nio.charset.StandardCharsets; public class LambdaHandler implements RequestStreamHandler { private static SpringBootLambdaContainerHandler<AwsProxyRequest, AwsProxyResponse> handler; private static final ObjectMapper objectMapper = new ObjectMapper(); static { try { handler = SpringBootLambdaContainerHandler.getAwsProxyHandler(Application.class); } catch (ContainerInitializationException e) { e.printStackTrace(); throw new RuntimeException("Could not initialize Spring Boot application", e); } } @Override public void handleRequest(InputStream input, OutputStream output, Context context) throws IOException { // 将输入流转为字符串,方便解析事件类型 String inputStr = new String(input.readAllBytes(), StandardCharsets.UTF_8); JsonNode eventNode = objectMapper.readTree(inputStr); // 通过source字段判断是否为EventBridge定时事件 if (eventNode.has("source") && "aws.events".equals(eventNode.get("source").asText())) { // 执行保活逻辑:打印日志 String keepAliveMsg = "Lambda Triggered"; context.getLogger().log(keepAliveMsg); // 返回成功响应给EventBridge AwsProxyResponse response = new AwsProxyResponse(200, null, keepAliveMsg); objectMapper.writeValue(output, response); } else { // 是API Gateway/ALB请求,交给Spring Boot容器处理原有HTTP逻辑 ByteArrayInputStream inputStream = new ByteArrayInputStream(inputStr.getBytes(StandardCharsets.UTF_8)); handler.proxyStream(inputStream, output, context); } } }
步骤2:优化EventBridge规则配置
使用ScheduleExpression时,EventPattern并非必须,可移除避免冗余:
MyEventBridgeRule: Type: AWS::Events::Rule Properties: ScheduleExpression: "cron(0/5 * * * ? *)" # 每5分钟触发一次 State: ENABLED Targets: - Arn: !GetAtt ProductInfoSamFunction.Arn Id: "MyLambdaBridgeTarget"
关键说明
- 通过事件的
source字段区分触发源:EventBridge事件的source固定为aws.events,API Gateway请求无此字段。 - 定时触发时直接执行保活逻辑,无需经过Spring Boot控制器,减少不必要的资源开销。
- 原有HTTP请求的处理逻辑完全保留,不影响API网关和Postman的正常访问。
内容的提问来源于stack exchange,提问作者Loren
相关产品推荐
相关产品推荐

