Spring Cloud函数可以与AWS Lambda基础图像一起使用吗



我试图通过容器映像在AWS Lambda上部署一个函数,但我找不到如何使用AWS Lambda基映像构建它的示例。Spring Cloud Function支持这种部署方法还是只支持jar部署?

是的,Spring Cloud函数将作为容器映像部署。无论使用Spring Cloud函数还是其他框架,过程都是一样的。

以下是lambda-libs GitHub项目中的Dockerfile示例。

# we'll use Amazon Linux 2 + Corretto 11 as our base
FROM public.ecr.aws/amazoncorretto/amazoncorretto:11 as base
# configure the build environment
FROM base as build
RUN yum install -y maven
WORKDIR /src
# cache and copy dependencies
ADD pom.xml .
RUN mvn dependency:go-offline dependency:copy-dependencies
# compile the function
ADD . .
RUN mvn package 
# copy the function artifact and dependencies onto a clean base
FROM base
WORKDIR /function
COPY --from=build /src/target/dependency/*.jar ./
COPY --from=build /src/target/*.jar ./
# configure the runtime startup as main
ENTRYPOINT [ "/usr/bin/java", "-cp", "./*", "com.amazonaws.services.lambda.runtime.api.client.AWSLambda" ]
# pass the name of the function handler as an argument to the runtime
# in this case it'll be the special Spring Cloud Function handler
CMD [ "example.App::sayHello" ]

我认为您所问的与AWS自定义运行时密切相关,事实上,我们确实对此提供了支持和示例-https://github.com/spring-cloud/spring-cloud-function/tree/main/spring-cloud-function-samples/function-sample-aws-custom

对于这两种方法,我都在Windows WSL2 Ubuntu 20.04发行版上运行了这个。Bash位于项目目录的根目录中。以下是我的两种Docker方法(我试图一步一步地弄清楚这一点(。

我的docker构建命令

docker build . -t <image name>

你可以在本地测试你的图像

#note external port = 9000, I left the default spring boot port of 8080
docker run -p 9000:8080 -t <build image name>

接近A

您可以在Maven或Gradle中的Docker之外编译JAR。然后我有一个docker构建文件,将其复制到Amazon发布的Java映像中。在我的案例中,我想使用Java17部署我的SpringCloud函数。

亚马逊使用更高的Java版本(如果需要,可以更低(发布他们的ECR基础图像

https://gallery.ecr.aws/lambda/java (find all Amazon Java images here)

在我的Docker构建文件中,我做了以下操作——注意,处理程序名称是最新版本的Spring Cloud Function的名称。

FROM public.ecr.aws/lambda/java:17
#the docker build command is running at my project root directory
COPY build/libs/<your jar name>.jar ${LAMBDA_TASK_ROOT}/lib/
CMD ["org.springframework.cloud.function.adapter.aws.FunctionInvoker::handleRequest"]

你应该能够在你的机器上本地运行这个映像,并测试它是否有效。

注意:JAR必须使用AWS lambda的Spring Cloud Function页面上的说明进行打包(https://docs.spring.io/spring-cloud-function/docs/current/reference/html/aws.html)。请参阅JAR布局注释部分。

方法B

我后来确实写了一个文件,在docker中编译了整个JAR,并在多步骤构建中将其粘贴在AmazonAWS Java映像中。由于Spring Boot附带了Maven/Gradle包装器,所以我只是使用了该包装器,而不是尝试在映像本身中安装Maven/GGradle。

# Use an official OpenJDK runtime as a parent image
FROM openjdk:17-jdk-slim
# Set the working directory to /app
WORKDIR /app
# Copy the application files <this is copies your entire java project dir>
COPY . /app
# Run the Gradle build
RUN ./gradlew clean build
#Copy the resulting JAR file to the ECR image
FROM public.ecr.aws/lambda/java:17
COPY --from=0 /app/build/libs/<INSERT project jar name>.jar ${LAMBDA_TASK_ROOT}/lib/
# Set the handler for AWS Lambda
CMD ["org.springframework.cloud.function.adapter.aws.FunctionInvoker::handleRequest"]

最新更新