前言:
今天在编译Flink的时候,一直失败,但是看网上的文章好像编译挺简单的,后来发现,其实是公司的网/国内的网不太行再加上我选择的maven远程仓库上缺了一些package。
之前我使用的远程仓库是mvnrepository.com,国内访问的速度还行,但是package不全。比较全的应该是中央仓库,它的repository id 是central,这个是maven默认的,我们不必配置。但是国内访问速度特别特别特别慢,基本下不动。因此最好能够有个proxy。但是全走proxy也不太好,毕竟还是没有直接走国内的那么快。最理想的情况就是,大部分的包我都能通过阿里云的maven仓下载,当阿里云没有这个包的时候,再走mvnrepository.com,还没有的话再走中央仓。
如何设置呢?
首先我们要知道,maven帮我们寻找jar包时选择的仓库的顺序。
maven搜索依赖的优先级:
本地仓库 > settings文件中profile定义的仓库 > 项目pom文件中profile标签中定义的仓库 > pom文件中repositories标签定义的仓库 > settings文件中定义的mirror镜像 > 默认的central
mirror和repository是什么关系?
mirror其实就是一个代替它所指定的repository的仓库,mirror通过指定mirrorOf标签的值(这个值就是repository的id,如果是*则表示所有repository)来代替一个存在的repository。假设有一个mirror,它的mirrorOf标签的值是central,它表示,任何要到central的下载都不行了,要走mirror制定的url去下载,即使没有mirror中没有这个package,maven也不会再去central下载了,会导致jar包下载失败。由于大部分的镜像地址(包括maven.aliyun.com)中的package都不怎么全,这就造成mirror这个配置有点鸡肋了。
配置:
1. 我删除了所有的mirror配置,并且在settings文件的profiles标签中定义了两个profile,一个是aliyun的仓库,一个是mvnrepository.com的仓库,aliyun放在第一位,因为我想让下载首先通过国内,mvnrepository放在第二个。结构如下:
<profiles>
<profile>
<id>aliyun_profile</id>
<repositories>
<repository>
<id>aliyun</id>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
</repository>
</repositories>
</profile>
<profile>
<id>mvnrepository_profile</id>
<repositories>
<repository>
<id>mvnrepository</id>
<url>https://mvnrepository.com/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
</repository>
</repositories>
</profile>
</profiles>
<!--激活profile-->
<activeProfiles>
<activeProfile>aliyun_profile</activeProfile>
<activeProfile>mvnrepository_profile</activeProfile>
</activeProfiles>
2. 因为以上两个仓库还是不太全,所以还是需要最后走中央仓库,因此,我在settings文件的proxies标签中定义一个proxy,proxy要屏蔽掉阿里云。
<proxies>
<proxy>
<id>socks5</id>
<active>true</active>
<protocol>socks5</protocol>
<host>127.0.0.1</host>
<port>1080</port>
<!--阿里云的下载不要通过proxy-->
<nonProxyHosts>*.aliyun.com*|172.*|10.*</nonProxyHosts>
</proxy>
</proxies>
如果proxy不生效,请检查你的maven home目录下的conf文件夹中settings文件是不是你的ide默认的配置settings文件。
在idea中使用的时候好像还是不生效,那就换个方法,在mvn clean install之前,先运行一下
export MAVEN_OPTS="-DproxySet=true -DsocksProxyHost=127.0.0.1 -DsocksProxyPort=1080 -DnonProxyHosts=*aliyun.com*|172.*|10.*"
不想proxy的时候,就
export MAVEN_OPTS="-DproxySet=false"