前提:
nexus的相關repository必須設置允許redeploy,參考下圖:
maven項目:
pom.xml中增加以下節點:
<distributionManagement> <repository> <id>nexus-3rd</id> <url>http://localhost:8081/nexus/content/repositories/thirdparty/</url> </repository> </distributionManagement>
一般上傳到nexus,為了方便他人查看源碼,也會上傳源碼包,建議在build/plugins節點里再增加以下節點,以便自動生成源碼jar包
1 <plugin> 2 <groupId>org.apache.maven.plugins</groupId> 3 <artifactId>maven-source-plugin</artifactId> 4 <executions> 5 <execution> 6 <id>attach-sources</id> 7 <goals> 8 <goal>jar</goal> 9 </goals> 10 </execution> 11 </executions> 12 </plugin>
上傳到nexus時是需要身份驗證的,所以還要在$M2_HOME/conf/settings.xml里添加以下內容:
1 <servers> 2 <server> 3 <username>admin</username> 4 <password>admin123</password> 5 <id>nexus-3rd</id> 6 </server> 7 </servers>
注意:這里的id必須與pom.xml中distributionManagement/repository/id保持一致。
最后一步,執行mvn命令:
mvn deploy -Dmaven.test.skip=true
后面的-Dmaven.test.skip=true意為跳過單元測試,可以酌情刪減,順利的話,以輸出中會看到類似內容:
... Uploading: http://localhost:8081/nexus/content/repositories/thirdparty/xxx/xxx.jar Uploaded: http://localhost:8081/nexus/content/repositories/thirdparty/xxx/xxx.jar (29582 KB at 18829.7 KB/sec) ...
gradle項目:
group 'my-company' version '1.0' def artifactId = "my-artifact" apply plugin: 'java' apply plugin: 'maven' ... //打包源代碼 task sourcesJar(type: Jar, dependsOn: classes) { classifier = 'sources' from sourceSets.main.allSource } artifacts { archives sourcesJar } ... //如果希望gradle install,安裝到.m2本地倉庫,參考下面的內容 install { repositories.mavenInstaller { pom.version = "$project.version" pom.artifactId = "$artifactId" pom.groupId = "$project.group" } } //上傳到nexus uploadArchives { repositories { mavenDeployer { repository(url: "http://localhost:8081/nexus/content/repositories/thirdparty") { authentication(userName: "admin", password: "admin123") } pom.version = "$project.version" pom.artifactId = "$artifactId" pom.groupId = "$project.group" } } }
然后gradle upload即可
不同分支(環境)的管理問題:
實際開發中,不同的環境通常會對應不同的git分支,比如:開發環境對應dev分支,測試環境對應test分支,生產環境對應master分支,dev環境測試通過后,合并到test分支,test分支完成后合并到master分支。
但是這樣有一個問題,nexus上的repository并沒有區分環境,如果程序員A在日常開發中,把dev分支的artifact上傳到了nexus,而部署人員在構建test環境的項目,這時從nexus上取到的就是dev環境里的東西,造成混亂,這里提供2種思路:
1)每個環境都搭一套nexus,各個環境完全隔離
優點:好管理,如果每個環境都通過統一的部署機器構建發布,結合host配置,可以將url也統一固定,只需要各環境部署機上的host配置好就行。
缺點:有點浪費資源
2)nexus只有一套,repository建多個,比如
http://localhost:8081/nexus/content/repositories/thirdparty_dev
http://localhost:8081/nexus/content/repositories/thirdparty_test
http://localhost:8081/nexus/content/repositories/thirdparty_prod
這樣相對比較節省資源一點,gradle中可以這樣配置:
def env = System.getProperty("env") ?: "local" uploadArchives { repositories { mavenDeployer { repository(url: "http://localhost:8081/nexus/content/repositories/thirdparty_$env") { authentication(userName: "admin", password: "admin123") } pom.version = "$project.version" pom.artifactId = "$artifactId" pom.groupId = "$project.group" } } }
然后gradle upload -Denv=dev 即可
另外:考慮到maven項目本機緩存的特性,建議在開發階段將版本號設置成SNAPSHOT,正式發布時,再去掉SNAPSHOT。詳情可見園友文章:理解Maven中的SNAPSHOT版本和正式版本
文章列表