1. 背景
微服务体系下,为了减少公共代码的重复编写,通常会有基础服务和工具服务,将这些基础服务和工具服务打成jar包,并发布到maven私服,其他业务服务直接在pom文件中引入依赖即可使用,可大大减少重复编码工作。
2. maven打包插件
2.1. spring-boot-maven-plugin
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<classifier>exec</classifier>
<mainClass>com.xxx.xxxApplication</mainClass>
</configuration>
</plugin>
2.2. maven-compiler-plugin
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
3. 修改maven setting配置
<!-- 配置私服账号密码 -->
<server>
<id>xxx-releases</id>
<username>admin</username>
<password>123456</password>
</server>
<server>
<id>xxx-nexus</id>
<username>admin</username>
<password>123456</password>
</server>
<!-- 配置私服镜像 -->
<mirrors>
<mirror>
<id>alimaven</id>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<mirrorOf>central</mirrorOf>
</mirror>
<mirror>
<id>xxx-nexus</id>
<name>nexus</name>
<mirrorOf>central</mirrorOf>
<url>http://nexus.xxxx.com:11081/repository/maven-public/</url>
</mirror>
</mirrors>
4. pom
- 插件
<build>
<plugins>
<!-- 打包 -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.xxx.xxxApplication</mainClass>
<classifier>exec</classifier>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- 上传源码 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.1</version>
<configuration>
<attach>true</attach>
</configuration>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
- 定义maven仓库
<!-- 定义maven仓库 -->
<distributionManagement>
<!-- 正式release仓库 -->
<repository>
<id>xxx-releases</id>
<name>maven仓库私服</name>
<url>http://nexus.xxx.com:11081/repository/maven-releases/</url>
</repository>
<!-- 快照snapshot仓库 -->
<snapshotRepository>
<id>xxx-nexus</id>
<url>http://nexus.xxx.com:11081/repository/maven-snapshots/</url>
<layout>default</layout>
</snapshotRepository>
</distributionManagement>
5. 注意事项
- pom文件中定义maven仓库时,
repository
的id
必须和 maven setting文件中配置私服账号密码的server
的id
保持一致; - pom文件如果定义快照
snapshotRepository
仓库,并且需要发布到snapshotRepository
仓库中时,该工程服务的版本号必须以-SNAPSHOT
结尾,例如:<groupId>com.xxx</groupId> <artifactId>xxx-xxx</artifactId> <version>1.0.0-SNAPSHOT</version>
- pom文件中定义maven仓库时,nexus私服的仓库
Type
必须是hosted
,否则发布时会报错
如果snapshotRepository
配置的是maven-public,则会报错,因为maven-public的Type是group,而不是hosted maven-snapshots
仓库发布时,版本号不变时,会根据时间以时间戳为后缀增量发布,从仓库拉取时,会拉取最新的版本,多用于开发环境等线下环境发布;maven-releases
仓库发布时,必须更换服务版本号,且不能有-SNAPSHOT
后缀。