最近的项目用到了分布式架构,分布式的好处自然不用多说,但有一个问题就是如何处理公共类或者说工具类,比方说时间格式转换、生成随机数、生成订单号这些开发人员都要用到的函数,不可能让每个开发人员都维护一个这样的工具类,因此,想到了利用打包成jar包并上传到maven仓库的方式,让开发人员可以共享公有类。
一、安装nexus
首先,先下载nexus,nexus是maven仓库的管理器:
wget https://sonatype-download.global.ssl.fastly.net/nexus/3/nexus-3.6.1-02-unix.tar.gz
下载完之后解压该文件:tar zxvf nexus-3.6.1-02-unix.tar.gz
切换到nexus-3.6.1-02/bin文件目录下:bin/nexus start
至此,nexus就安装完成,并且已经在服务器上启动。
在浏览器上输入http://ip:8081/(nexus默认的端口号是8081),进入nexus,sign in登录,默认的用户名是admin,密码是admin123;
二、创建私有仓库
登录成功之后,点击左上方的小齿轮,选择Repository->Repostitories->create repository,创建仓库:
进入下一步,选择maven2(hosted);
hosted:本地仓库,通常我们会部署自己的构件到这一类型的仓库。比如公司的第二方库。
proxy:代理仓库,它们被用来代理远程的公共仓库,如maven中央仓库。
group:仓库组,用来合并多个hosted/proxy仓库。
进入下一步,输入仓库的基本属性;
点击save,创建仓库成功。
三、上传jar包
打开maven对应的setting.xml,添加如下节点:
打开需要打包的项目的pom,添加如下节点,url对应的是maven私库的地址;
<distributionManagement>
<repository>
<id>maven-releases</id>
<url>http://ip+:8081/repository/maven-third-party/releases/</url>
</repository>
</distributionManagement>
添加打包插件:
<build>
<plugins>
<!-- 打jar包插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<excludes>
<exclude>**/*.properties</exclude>
</excludes>
</configuration>
</plugin>
<!-- 打包源码插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.0.1</version>
<configuration>
<attach>true</attach>
</configuration>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
配置完成后,在终端输入:mvn clean source:jar package,进行打包;mvn deploy -e,部署到maven私有库;
部署成功后,即可在nexus控制面板看到jar包:
四、在其他项目中引入私库中的jar
添加如下节点,项目会先从私库中查找dependency,如果找不到,会从maven的中央仓库中下载;
<repositories>
<repository>
<id>maven-releases</id>
<name>maven-third-party</name>
<url>http://ip+:8081/repository/maven-third-party/releases/</url>
</repository>
</repositories>
加入依赖:
<dependency>
<groupId>myUtils</groupId>
<artifactId>myUtils</artifactId>
<version>1.0</version>
</dependency>
下载完成后,即可在项目中引用该jar包。