本文承接RDS for MySQL,前面我们已经部署好了数据库服务,并测试了连通性,这里则开始部署我们的代码,并连通rds服务.
可以以官方demo为例,或者引入aws提供的aws-serverless-java-container-spring组件,进行部分改造即可。
这里介绍如何在我们的工程里添加lambda支持,我们的已有工程为Spring框架,首先在pom.xml中引入serverless依赖.
image
接着需要添加StreamLambdaHandler.class,SpringApiConfig.class.
image
两者功能在这里简单介绍一下,RequestStreamHandler是aws lambda 应用程序的入口,我们声明的StreamLambdaHandler继承了RequestStreamHandler,并加载了初始化时,需要扫描的方法类,这些类都在SpringApiConfig中注解引入。
RequestStreamHandler.class
public class StreamLambdaHandler implements RequestStreamHandler {
private static SpringLambdaContainerHandler handler;
static {
try {
handler = SpringLambdaContainerHandler.getAwsProxyHandler(SpringApiConfig.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 framework", e);
}
}
@Override
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context)
throws IOException {
handler.proxyStream(inputStream, outputStream, context);
}
}
在SpringApiConfig中,一次性引入多个需要调用的方法类,否则发布程序后,lambda将无法读取到相应的类。
SpringApiConfig.class:
@Configuration
// We use direct @Import instead of @ComponentScan