Maven 多仓库和镜像配置

因为之前maven配置的一直都是公司的私服仓库,今天 拉 JMH包发现拉不到,于是考虑配置多个仓库,可以满足工作以及日常开发需求,顺便梳理 mirrorsrepository 的区别

maven 设置多个仓库

有两种不同的方式可以指定多个存储库的使用。第一种方法是在 POM 中指定要使用的存储库。这在构建概要文件内部和外部都支持

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
xml复制代码<project>
...
<repositories>
<repository>
<id>my-repo1</id>
<name>your custom repo</name>
<url>http://jarsm2.dyndns.dk</url>
</repository>
<repository>
<id>my-repo2</id>
<name>your custom repo</name>
<url>http://jarsm2.dyndns.dk</url>
</repository>
</repositories>
...
</project>

另一种指定多个存储库的方法是在${user.home}/.m2/settings.xml或者 ${maven.home}/conf/settings.xml文件中 新建 profile信息 如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
xml复制代码<settings>
...
<profiles>
// 第一个仓库地址
<profile>
<id>nexus</id>
<repositories>
<repository>
<id>my-repo2</id>
<name>your custom repo</name>
<url>http://jarsm2.dyndns.dk</url>
</repository>
</repositories>
</profile>
// 第二个仓库地址
<profile>
<id>aliyun</id>
<repositories>
<repository>
<id>aliyun</id>
<url>https://maven.aliyun.com/repository/public</url>
<releases><enabled>true</enabled></releases>
<snapshots><enabled>true</enabled></snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>aliyun</id>
<url>https://maven.aliyun.com/repository/public</url>
<releases><enabled>true</enabled></releases>
<snapshots><enabled>true</enabled></snapshots>
</pluginRepository>
</pluginRepositories>
</profile>
</profiles>

<activeProfiles>
<activeProfile>nexus</activeProfile>
<activeProfile>aliyun</activeProfile>
</activeProfiles>
...
</settings>

如果您在profiles 中指定 repository 存储库,需要激活该特定profiles,我们通过在 activeProfiles 中进行配置

你也可以通过执行以下命令来激活这个配置文件:

1
erlang复制代码mvn -Pnexus ...

正常maven 的settings.xml配置完成profiles之后,可以在idea中进行切换

设置镜像

镜像 相当于拦截机。它拦截 maven 对远程存储库的请求,将请求中的远程存储库地址重定向到镜像中配置的地址。它主要提供了一个方便的方式来切换远程仓库地址。例如,在公司工作时,使用电信网络,连接到电信仓库。当我回家的时候,是联通的网络。我想连接联通的仓库。我可以通过镜像配置将我的项目的仓库地址变成联通,而不是在特定的项目配置文件中逐个地改变地址

1
2
3
4
5
6
7
8
9
10
11
12
xml复制代码<settings>
...
<mirrors>
<mirror>
<id>aliyun</id>
<name>Maven Repository Manager running on repo.mycompany.com</name>
<url>http://repo.mycompany.com/proxy</url>
<mirrorOf>*</mirrorOf>
</mirror>
</mirrors>
...
</settings>

配置说明:

id: 镜像的唯一标识•mirrorOf: 指定镜像规则,什么情况下从镜像仓库拉取,•*: 匹配所有,所有内容都从镜像拉取•external:*: 除了本地缓存的所有从镜像仓库拉取idea•repo,repo1: repo 或者 repo1 ,这里的 repo 指的仓库 ID•*,!repo1: 除了 repo1 的所有仓库•name: 名称描述•url: 地址

示列: 针对aliyun 仓库进行设置镜像重定向到镜像中配置的地址

1
2
3
4
5
6
7
8
xml复制代码  <mirrors>
<mirror>
<id>aliyun</id>
<mirrorOf>aliyun</mirrorOf>
<name>ppd mirror</name>
<url>http://repo.mycompany.com/proxy</url>
</mirror>
</mirrors>

image-20210805154919762

这个时候会发现 虽然 repository 配置的是正确aliyun 地址,但是由于mirror镜像拦截的原因重定向新的url.

image-20210805155037900

mirrors 与profiles 设置repository的区别

mirror 与 repository 不同的是,假如配置同一个 repository 多个 mirror 时,相互之间是备份关系,只有当仓库连不上时才会切换到另

一个,而如果能连上但是找不到依赖时是不会尝试下一个 mirror 地址的

reference

maven.apache.org/guides/mini…

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%