使用FAT jar部署Google Cloud Function(v2)失败求助
一、搞定com.app:Base:jar:1.0-SNAPSHOT依赖找不到的问题
先把Base模块装到本地Maven仓库
因为Share是子模块,Maven构建时得从本地仓库拉Base的依赖。直接在父项目根目录跑:mvn clean install -pl Base -am解释:
-pl Base指定只构建Base模块,-am会自动构建Base依赖的父POM,跑完后Base的jar包就会出现在~/.m2/repository/com/app/Base/1.0-SNAPSHOT/里。检查Share模块的依赖配置
打开Share的pom.xml,确保对Base的依赖是下面这样,范围必须是compile(这样才会打包进fat jar):<dependency> <groupId>com.app</groupId> <artifactId>Base</artifactId> <version>1.0-SNAPSHOT</version> <scope>compile</scope> </dependency>确认Fat Jar的打包插件配置对不对
GCF v2构建fat jar要么用Google官方的插件,要么用shade插件,得确保插件把Base的类打包进去:- 用Google官方插件的话,配置要带
functionTarget:<plugin> <groupId>com.google.cloud.tools</groupId> <artifactId>google-cloud-functions-maven-plugin</artifactId> <version>2.1.0</version> <configuration> <functionTarget>com.app.share.YourFunctionClass</functionTarget> <deployStage>production</deployStage> </configuration> </plugin> - 用shade插件的话,要明确包含Base模块:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>3.4.1</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <createDependencyReducedPom>false</createDependencyReducedPom> <includes> <include>com.app:Base</include> </includes> </configuration> </execution> </executions> </plugin>
- 用Google官方插件的话,配置要带
部署时指定正确的Jar文件
别用target目录下的普通jar,直接指定deployment目录里的fat jar:gcloud functions deploy your-function-name \ --runtime java17 \ --entry-point com.app.share.YourFunctionClass \ --jar target/deployment/share-1.0-SNAPSHOT.jar
二、解决父POMcom.app:Parent:pom:1.0-SNAPSHOT找不到的问题
修正Share模块的父POM引用
Share的pom.xml里父POM的配置必须加<relativePath>,指向顶层父POM的位置,不然Maven会去远程仓库找本地快照版本的父POM:<parent> <groupId>com.app</groupId> <artifactId>Parent</artifactId> <version>1.0-SNAPSHOT</version> <!-- 父POM在Share的上层目录,所以用../pom.xml --> <relativePath>../pom.xml</relativePath> </parent>把父POM装到本地仓库
在父项目根目录跑:mvn clean install -N-N表示只装父POM,不构建子模块,确保父POM的pom文件出现在~/.m2/repository/com/app/Parent/1.0-SNAPSHOT/里。检查本地仓库的父POM文件
去~/.m2/repository/com/app/Parent/1.0-SNAPSHOT/看看有没有Parent-1.0-SNAPSHOT.pom,没有的话重新跑上面的安装命令。
验证步骤
- 在父项目根目录跑
mvn clean install,确保所有模块都构建成功并装到本地仓库。 - 进入Share模块,跑
mvn package,然后用jar tf target/deployment/share-1.0-SNAPSHOT.jar命令查看jar里有没有com/app/base/开头的类,有就说明打包对了。 - 再执行部署命令,应该就不会报依赖找不到的错了。
内容的提问来源于stack exchange,提问作者Mike Dee

