Maven私有仓库搭建与配置指南

Maven私有仓库搭建与配置指南

目录

  • [1. 概述](#1. 概述)
  • [2. 私有Maven仓库选型](#2. 私有Maven仓库选型)
  • [3. Nexus Repository搭建](#3. Nexus Repository搭建)
    • [3.1 使用Docker部署Nexus](#3.1 使用Docker部署Nexus)
    • [3.2 使用Kubernetes部署Nexus](#3.2 使用Kubernetes部署Nexus)
  • [4. Nexus仓库配置](#4. Nexus仓库配置)
    • [4.1 创建仓库](#4.1 创建仓库)
    • [4.2 创建用户和权限](#4.2 创建用户和权限)
  • [5. Maven客户端配置](#5. Maven客户端配置)
    • [5.1 配置settings.xml](#5.1 配置settings.xml)
    • [5.2 配置项目pom.xml](#5.2 配置项目pom.xml)
  • [6. 发布构件到私有仓库](#6. 发布构件到私有仓库)
    • [6.1 使用Maven Deploy插件](#6.1 使用Maven Deploy插件)
    • [6.2 发布第三方jar包](#6.2 发布第三方jar包)
  • [7. 从私有仓库拉取依赖](#7. 从私有仓库拉取依赖)
  • [8. 常见问题与解决方案](#8. 常见问题与解决方案)
  • [9. 最佳实践](#9. 最佳实践)

1. 概述

1.1 为什么需要私有Maven仓库?

私有Maven仓库在企业级开发中扮演着重要角色:

  1. 加速构建:缓存公共仓库的依赖,减少外网下载时间
  2. 内部共享:团队内部共享自研组件和工具包
  3. 安全控制:控制依赖版本,避免使用不安全的组件
  4. 离线开发:在无网络环境下也能进行开发
  5. 第三方jar管理:统一管理第三方或商业jar包
  6. 版本控制:统一管理依赖版本,避免版本冲突

1.2 Maven仓库类型

  • hosted(宿主仓库):存储本地上传的构件

    • releases:存储正式发布版本
    • snapshots:存储快照版本
  • proxy(代理仓库):代理远程仓库,如Maven Central

  • group(仓库组):聚合多个仓库,提供统一访问入口


2. 私有Maven仓库选型

2.1 主流方案对比

产品 开源版本 企业版本 特点 推荐场景
Nexus Repository 功能强大,社区活跃 中大型企业
JFrog Artifactory 支持多种格式,云原生 大型企业
Apache Archiva 轻量级,易部署 小型团队
阿里云Maven私服 托管服务,免运维 快速上线

2.2 本文选择

本指南以 Nexus Repository 3 为例,原因:

  • 开源免费
  • 功能完善
  • 社区活跃
  • 文档丰富
  • 易于部署和维护

3. Nexus Repository搭建

3.1 使用Docker部署Nexus

3.1.1 快速部署
bash 复制代码
# 创建数据目录
mkdir -p /data/nexus-data
chmod -R 777 /data/nexus-data

# 运行Nexus容器
docker run -d \
  --name nexus3 \
  --restart=always \
  -p 8081:8081 \
  -v /data/nexus-data:/nexus-data \
  sonatype/nexus3:latest
3.1.2 使用Docker Compose部署

创建 docker-compose.yml

yaml 复制代码
version: '3.8'

services:
  nexus:
    image: sonatype/nexus3:3.63.0
    container_name: nexus3
    restart: always
    ports:
      - "8081:8081"     # Web UI端口
      - "8082:8082"     # Docker私有仓库端口(可选)
    volumes:
      - nexus-data:/nexus-data
    environment:
      - INSTALL4J_ADD_VM_PARAMS=-Xms2g -Xmx2g -XX:MaxDirectMemorySize=3g
    ulimits:
      nofile:
        soft: 65536
        hard: 65536

volumes:
  nexus-data:
    driver: local

启动服务:

bash 复制代码
# 启动Nexus
docker-compose up -d

# 查看日志
docker-compose logs -f nexus

# 等待启动完成(首次启动需要几分钟)
docker-compose logs nexus | grep "Started Sonatype Nexus"
3.1.3 获取初始密码
bash 复制代码
# 查看初始admin密码
docker exec nexus3 cat /nexus-data/admin.password

# 或者在宿主机查看
cat /data/nexus-data/admin.password
3.1.4 访问Nexus
  1. 浏览器访问:http://your-server-ip:8081
  2. 点击右上角 Sign in
  3. 使用默认账号:
    • 用户名:admin
    • 密码:从上述命令获取
  4. 首次登录会提示修改密码并配置匿名访问

3.2 使用Kubernetes部署Nexus

3.2.1 创建命名空间
bash 复制代码
kubectl create namespace nexus
3.2.2 创建PVC(持久化存储)

创建 nexus-pvc.yaml

yaml 复制代码
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: nexus-pvc
  namespace: nexus
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 100Gi
  storageClassName: alicloud-disk-ssd  # 根据实际情况修改

应用配置:

bash 复制代码
kubectl apply -f nexus-pvc.yaml
3.2.3 创建Deployment

创建 nexus-deployment.yaml

yaml 复制代码
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nexus3
  namespace: nexus
  labels:
    app: nexus3
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nexus3
  template:
    metadata:
      labels:
        app: nexus3
    spec:
      containers:
      - name: nexus3
        image: sonatype/nexus3:3.63.0
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 8081
          name: web
          protocol: TCP
        env:
        - name: INSTALL4J_ADD_VM_PARAMS
          value: "-Xms2g -Xmx2g -XX:MaxDirectMemorySize=3g"
        resources:
          requests:
            memory: "4Gi"
            cpu: "1000m"
          limits:
            memory: "6Gi"
            cpu: "2000m"
        volumeMounts:
        - name: nexus-data
          mountPath: /nexus-data
        livenessProbe:
          httpGet:
            path: /
            port: 8081
          initialDelaySeconds: 180
          periodSeconds: 30
          timeoutSeconds: 10
        readinessProbe:
          httpGet:
            path: /
            port: 8081
          initialDelaySeconds: 60
          periodSeconds: 30
          timeoutSeconds: 10
      volumes:
      - name: nexus-data
        persistentVolumeClaim:
          claimName: nexus-pvc

应用配置:

bash 复制代码
kubectl apply -f nexus-deployment.yaml
3.2.4 创建Service

创建 nexus-service.yaml

yaml 复制代码
apiVersion: v1
kind: Service
metadata:
  name: nexus3
  namespace: nexus
  labels:
    app: nexus3
spec:
  type: ClusterIP
  ports:
  - port: 8081
    targetPort: 8081
    protocol: TCP
    name: web
  selector:
    app: nexus3

应用配置:

bash 复制代码
kubectl apply -f nexus-service.yaml
3.2.5 创建Ingress(可选)

创建 nexus-ingress.yaml

yaml 复制代码
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: nexus3
  namespace: nexus
  annotations:
    nginx.ingress.kubernetes.io/proxy-body-size: "0"
    nginx.ingress.kubernetes.io/proxy-read-timeout: "600"
    nginx.ingress.kubernetes.io/proxy-send-timeout: "600"
spec:
  ingressClassName: nginx
  rules:
  - host: nexus.yourdomain.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: nexus3
            port:
              number: 8081
  tls:
  - hosts:
    - nexus.yourdomain.com
    secretName: nexus-tls-secret  # 需要提前创建SSL证书

应用配置:

bash 复制代码
kubectl apply -f nexus-ingress.yaml
3.2.6 验证部署
bash 复制代码
# 查看Pod状态
kubectl get pods -n nexus

# 查看日志
kubectl logs -f deployment/nexus3 -n nexus

# 获取初始密码
kubectl exec -n nexus deployment/nexus3 -- cat /nexus-data/admin.password

4. Nexus仓库配置

4.1 创建仓库

登录Nexus后,进行仓库配置。

4.1.1 创建Blob Store(存储)
  1. 点击左侧菜单 Settings(齿轮图标)
  2. 选择 Repository > Blob Stores
  3. 点击 Create blob store
  4. 选择类型:File
  5. 配置:
    • Name : maven-releases-blob
    • Path: 默认即可
  6. 点击 Create blob store

重复以上步骤创建:

  • maven-snapshots-blob
  • maven-central-blob
4.1.2 创建Hosted仓库(releases)
  1. 点击 Repository > Repositories

  2. 点击 Create repository

  3. 选择 maven2 (hosted)

  4. 配置:

    复制代码
    Name: maven-releases
    Version policy: Release
    Layout policy: Strict
    Blob store: maven-releases-blob
    Deployment policy: Allow redeploy (生产环境建议Disable redeploy)
  5. 点击 Create repository

4.1.3 创建Hosted仓库(snapshots)
  1. 点击 Create repository

  2. 选择 maven2 (hosted)

  3. 配置:

    复制代码
    Name: maven-snapshots
    Version policy: Snapshot
    Layout policy: Strict
    Blob store: maven-snapshots-blob
    Deployment policy: Allow redeploy
  4. 点击 Create repository

4.1.4 创建Proxy仓库(代理Maven Central)
  1. 点击 Create repository

  2. 选择 maven2 (proxy)

  3. 配置:

    复制代码
    Name: maven-central
    Version policy: Release
    Remote storage: https://repo1.maven.org/maven2/
    Blob store: maven-central-blob
    Maximum component age: 1440 (24小时)
    Maximum metadata age: 1440
  4. 点击 Create repository

4.1.5 创建Proxy仓库(代理阿里云Maven)

推荐添加阿里云镜像以加速国内访问:

  1. 点击 Create repository

  2. 选择 maven2 (proxy)

  3. 配置:

    复制代码
    Name: maven-aliyun
    Version policy: Release
    Remote storage: https://maven.aliyun.com/repository/public
    Blob store: maven-central-blob
  4. 点击 Create repository

4.1.6 创建Group仓库(聚合所有仓库)
  1. 点击 Create repository

  2. 选择 maven2 (group)

  3. 配置:

    复制代码
    Name: maven-public
    Blob store: default
  4. Group 部分,将以下仓库添加到 Members (顺序很重要):

    复制代码
    1. maven-releases
    2. maven-snapshots
    3. maven-aliyun
    4. maven-central
  5. 点击 Create repository

4.1.7 仓库结构总览
复制代码
maven-public (group)
├── maven-releases (hosted)     # 内部releases版本
├── maven-snapshots (hosted)    # 内部snapshots版本
├── maven-aliyun (proxy)        # 阿里云代理
└── maven-central (proxy)       # Maven Central代理

4.2 创建用户和权限

4.2.1 创建部署用户(用于发布构件)
  1. 点击 Security > Users

  2. 点击 Create local user

  3. 配置:

    复制代码
    ID: deployment
    First name: Deployment
    Last name: User
    Email: deployment@yourdomain.com
    Status: Active
    Roles: nx-deploy (添加部署权限)
    Password: 设置强密码
  4. 点击 Create local user

4.2.2 创建开发者用户(用于拉取依赖)
  1. 点击 Create local user

  2. 配置:

    复制代码
    ID: developer
    First name: Developer
    Last name: User
    Email: developer@yourdomain.com
    Status: Active
    Roles: nx-anonymous (只读权限)
    Password: 设置密码
  3. 点击 Create local user

4.2.3 配置匿名访问(可选)

如果希望内网用户无需认证即可拉取依赖:

  1. 点击 Security > Anonymous Access
  2. 勾选 Allow anonymous users to access the server
  3. 点击 Save

注意:生产环境建议禁用匿名访问,使用账号密码认证。


5. Maven客户端配置

5.1 配置settings.xml

Maven的全局配置文件通常位于:

  • Windows: C:\Users\{用户名}\.m2\settings.xml
  • Linux/Mac: ~/.m2/settings.xml
5.1.1 完整配置示例
xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                              http://maven.apache.org/xsd/settings-1.0.0.xsd">
  
  <!-- 本地仓库路径 -->
  <localRepository>D:/maven-repository</localRepository>
  
  <!-- 服务器认证信息 -->
  <servers>
    <!-- Nexus部署用户(用于发布构件) -->
    <server>
      <id>nexus-releases</id>
      <username>deployment</username>
      <password>your-deployment-password</password>
    </server>
    
    <server>
      <id>nexus-snapshots</id>
      <username>deployment</username>
      <password>your-deployment-password</password>
    </server>
    
    <!-- Nexus下载用户(用于拉取依赖) -->
    <server>
      <id>nexus-public</id>
      <username>developer</username>
      <password>your-developer-password</password>
    </server>
  </servers>
  
  <!-- 镜像配置 -->
  <mirrors>
    <!-- 配置Nexus为所有仓库的镜像 -->
    <mirror>
      <id>nexus-public</id>
      <mirrorOf>*</mirrorOf>
      <name>Nexus Public Repository</name>
      <url>http://your-nexus-server:8081/repository/maven-public/</url>
    </mirror>
  </mirrors>
  
  <!-- Profile配置 -->
  <profiles>
    <profile>
      <id>nexus</id>
      <repositories>
        <!-- 从Nexus下载releases版本 -->
        <repository>
          <id>nexus-public</id>
          <name>Nexus Public Repository</name>
          <url>http://your-nexus-server:8081/repository/maven-public/</url>
          <releases>
            <enabled>true</enabled>
            <updatePolicy>daily</updatePolicy>
          </releases>
          <snapshots>
            <enabled>true</enabled>
            <updatePolicy>always</updatePolicy>
          </snapshots>
        </repository>
      </repositories>
      
      <!-- 从Nexus下载插件 -->
      <pluginRepositories>
        <pluginRepository>
          <id>nexus-public</id>
          <name>Nexus Public Repository</name>
          <url>http://your-nexus-server:8081/repository/maven-public/</url>
          <releases>
            <enabled>true</enabled>
          </releases>
          <snapshots>
            <enabled>true</enabled>
          </snapshots>
        </pluginRepository>
      </pluginRepositories>
    </profile>
  </profiles>
  
  <!-- 激活profile -->
  <activeProfiles>
    <activeProfile>nexus</activeProfile>
  </activeProfiles>
  
</settings>
5.1.2 配置说明

1. localRepository

  • 指定本地Maven仓库路径
  • 下载的依赖会存储在这里

2. servers

  • 配置Nexus的认证信息
  • <id> 必须与 pom.xml 中的 <id> 匹配
  • 分别配置releases和snapshots的认证

3. mirrors

  • 配置镜像,将所有Maven请求重定向到Nexus
  • <mirrorOf>*</mirrorOf> 表示代理所有仓库
  • 也可以配置为 <mirrorOf>central</mirrorOf> 只代理中央仓库

4. profiles

  • 定义Maven配置文件
  • 配置仓库地址和插件仓库地址
  • updatePolicy 配置更新策略:
    • always: 每次构建都检查更新
    • daily: 每天检查一次(默认)
    • never: 从不检查更新

5.2 配置项目pom.xml

5.2.1 基础配置

在项目的 pom.xml 中添加发布配置:

xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    
    <!-- 项目坐标 -->
    <groupId>com.tigeriot</groupId>
    <artifactId>product-manager-service</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    
    <name>Product Manager Service</name>
    <description>产品管理服务</description>
    
    <!-- 发布配置 -->
    <distributionManagement>
        <!-- releases版本发布地址 -->
        <repository>
            <id>nexus-releases</id>
            <name>Nexus Release Repository</name>
            <url>http://your-nexus-server:8081/repository/maven-releases/</url>
        </repository>
        
        <!-- snapshots版本发布地址 -->
        <snapshotRepository>
            <id>nexus-snapshots</id>
            <name>Nexus Snapshot Repository</name>
            <url>http://your-nexus-server:8081/repository/maven-snapshots/</url>
        </snapshotRepository>
    </distributionManagement>
    
    <!-- 仓库配置(用于下载依赖) -->
    <repositories>
        <repository>
            <id>nexus-public</id>
            <name>Nexus Public Repository</name>
            <url>http://your-nexus-server:8081/repository/maven-public/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>
    
    <!-- 插件仓库配置 -->
    <pluginRepositories>
        <pluginRepository>
            <id>nexus-public</id>
            <name>Nexus Public Repository</name>
            <url>http://your-nexus-server:8081/repository/maven-public/</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>
    
    <!-- 构建配置 -->
    <build>
        <plugins>
            <!-- Maven Deploy插件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>3.1.1</version>
            </plugin>
            
            <!-- Maven Source插件(发布源码) -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>3.3.0</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <phase>verify</phase>
                        <goals>
                            <goal>jar-no-fork</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            
            <!-- Maven Javadoc插件(发布文档) -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>3.6.3</version>
                <configuration>
                    <encoding>UTF-8</encoding>
                    <charset>UTF-8</charset>
                    <docencoding>UTF-8</docencoding>
                    <!-- 忽略Javadoc错误 -->
                    <failOnError>false</failOnError>
                    <doclint>none</doclint>
                </configuration>
                <executions>
                    <execution>
                        <id>attach-javadocs</id>
                        <phase>verify</phase>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    
</project>
5.2.2 父POM配置(多模块项目)

对于多模块项目,在父 pom.xml 中配置:

xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    
    <groupId>com.tigeriot</groupId>
    <artifactId>microservices-parent</artifactId>
    <version>1.0.0</version>
    <packaging>pom</packaging>
    
    <name>Microservices Parent</name>
    
    <!-- 子模块 -->
    <modules>
        <module>product-manager-service</module>
        <module>user-service</module>
        <module>order-service</module>
    </modules>
    
    <!-- 发布配置(子模块会继承) -->
    <distributionManagement>
        <repository>
            <id>nexus-releases</id>
            <name>Nexus Release Repository</name>
            <url>http://your-nexus-server:8081/repository/maven-releases/</url>
        </repository>
        <snapshotRepository>
            <id>nexus-snapshots</id>
            <name>Nexus Snapshot Repository</name>
            <url>http://your-nexus-server:8081/repository/maven-snapshots/</url>
        </snapshotRepository>
    </distributionManagement>
    
    <!-- 统一依赖管理 -->
    <dependencyManagement>
        <dependencies>
            <!-- Spring Boot -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.7.18</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>3.1.1</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
    
</project>

6. 发布构件到私有仓库

6.1 使用Maven Deploy插件

6.1.1 发布SNAPSHOT版本

确保 pom.xml 中版本号包含 -SNAPSHOT 后缀:

xml 复制代码
<version>1.0.0-SNAPSHOT</version>

执行发布命令:

bash 复制代码
# 清理并发布
mvn clean deploy

# 跳过测试发布
mvn clean deploy -DskipTests

# 指定profile发布
mvn clean deploy -P nexus -DskipTests
6.1.2 发布RELEASE版本
  1. 修改 pom.xml 版本号,去掉 -SNAPSHOT
xml 复制代码
<version>1.0.0</version>
  1. 执行发布命令:
bash 复制代码
mvn clean deploy -DskipTests
  1. 发布后建议立即升级版本并添加 -SNAPSHOT
xml 复制代码
<version>1.0.1-SNAPSHOT</version>
6.1.3 只发布不构建

如果已经构建过,只想发布:

bash 复制代码
mvn deploy:deploy-file \
  -DgroupId=com.tigeriot \
  -DartifactId=product-manager-service \
  -Dversion=1.0.0 \
  -Dpackaging=jar \
  -Dfile=target/product-manager-service-1.0.0.jar \
  -DrepositoryId=nexus-releases \
  -Durl=http://your-nexus-server:8081/repository/maven-releases/
6.1.4 发布多模块项目

在父模块根目录执行:

bash 复制代码
# 发布所有子模块
mvn clean deploy -DskipTests

# 只发布某个子模块
cd product-manager-service
mvn clean deploy -DskipTests

6.2 发布第三方jar包

有时需要发布第三方提供的jar包(没有源码)。

6.2.1 使用命令行发布
bash 复制代码
mvn deploy:deploy-file \
  -DgroupId=com.thirdparty \
  -DartifactId=third-party-lib \
  -Dversion=1.0.0 \
  -Dpackaging=jar \
  -Dfile=/path/to/third-party-lib-1.0.0.jar \
  -DrepositoryId=nexus-releases \
  -Durl=http://your-nexus-server:8081/repository/maven-releases/

参数说明:

  • groupId: 自定义group ID
  • artifactId: 自定义artifact ID
  • version: 版本号
  • packaging: 打包类型(jar/war/pom等)
  • file: jar文件路径
  • repositoryId: settings.xml中配置的server ID
  • url: Nexus仓库地址
6.2.2 同时发布jar和pom
bash 复制代码
mvn deploy:deploy-file \
  -DgroupId=com.thirdparty \
  -DartifactId=third-party-lib \
  -Dversion=1.0.0 \
  -Dpackaging=jar \
  -Dfile=/path/to/third-party-lib-1.0.0.jar \
  -DpomFile=/path/to/third-party-lib-1.0.0.pom \
  -DrepositoryId=nexus-releases \
  -Durl=http://your-nexus-server:8081/repository/maven-releases/
6.2.3 使用Nexus UI上传
  1. 登录Nexus
  2. 点击左侧 Upload
  3. 选择仓库:maven-releases
  4. 填写GAV信息:
    • Group : com.thirdparty
    • Artifact : third-party-lib
    • Version : 1.0.0
    • Packaging : jar
  5. 选择jar文件
  6. 可选:上传pom文件和sources
  7. 点击 Upload
6.2.4 批量上传脚本

创建 upload-third-party.sh

bash 复制代码
#!/bin/bash

NEXUS_URL="http://your-nexus-server:8081/repository/maven-releases/"
REPO_ID="nexus-releases"

# 上传单个jar
upload_jar() {
  local group=$1
  local artifact=$2
  local version=$3
  local file=$4
  
  echo "Uploading $artifact-$version..."
  mvn deploy:deploy-file \
    -DgroupId=$group \
    -DartifactId=$artifact \
    -Dversion=$version \
    -Dpackaging=jar \
    -Dfile=$file \
    -DrepositoryId=$REPO_ID \
    -Durl=$NEXUS_URL
}

# 示例:上传多个jar包
upload_jar "com.oracle" "ojdbc8" "19.3.0.0" "libs/ojdbc8-19.3.0.0.jar"
upload_jar "com.alibaba" "druid" "1.2.20" "libs/druid-1.2.20.jar"
upload_jar "com.github" "pagehelper" "5.3.2" "libs/pagehelper-5.3.2.jar"

echo "All uploads completed!"

执行脚本:

bash 复制代码
chmod +x upload-third-party.sh
./upload-third-party.sh

7. 从私有仓库拉取依赖

7.1 在项目中使用私有仓库的依赖

确保 settings.xmlpom.xml 已正确配置后,直接在 pom.xml 中添加依赖:

xml 复制代码
<dependencies>
    <!-- 从私有仓库拉取内部组件 -->
    <dependency>
        <groupId>com.tigeriot</groupId>
        <artifactId>common-utils</artifactId>
        <version>1.0.0</version>
    </dependency>
    
    <!-- 拉取SNAPSHOT版本 -->
    <dependency>
        <groupId>com.tigeriot</groupId>
        <artifactId>api-gateway</artifactId>
        <version>1.0.0-SNAPSHOT</version>
    </dependency>
    
    <!-- 从私有仓库拉取第三方jar -->
    <dependency>
        <groupId>com.thirdparty</groupId>
        <artifactId>third-party-lib</artifactId>
        <version>1.0.0</version>
    </dependency>
</dependencies>

7.2 更新依赖

bash 复制代码
# 更新所有依赖(包括SNAPSHOT)
mvn clean install -U

# 或者
mvn clean install --update-snapshots

# 查看依赖树
mvn dependency:tree

# 下载源码和文档
mvn dependency:sources
mvn dependency:resolve -Dclassifier=javadoc

7.3 清理本地缓存

如果遇到依赖问题,可以清理本地缓存:

bash 复制代码
# 清理特定依赖
mvn dependency:purge-local-repository \
  -DmanualInclude=com.tigeriot:common-utils

# 清理所有本地依赖并重新下载
mvn dependency:purge-local-repository -DreResolve=false

8. 常见问题与解决方案

8.1 认证失败

问题:发布时提示401 Unauthorized

解决方案

  1. 检查 settings.xml 中的 <server> 配置
  2. 确保 <id>pom.xml 中的 <repository><id> 匹配
  3. 验证用户名密码是否正确
  4. 检查Nexus中用户是否有部署权限
xml 复制代码
<!-- settings.xml -->
<server>
  <id>nexus-releases</id>  <!-- 必须与pom.xml中的id一致 -->
  <username>deployment</username>
  <password>correct-password</password>
</server>

8.2 无法下载依赖

问题:Maven无法从Nexus下载依赖

解决方案

  1. 检查Nexus服务是否运行
  2. 验证网络连接和防火墙
  3. 检查 settings.xml 中的镜像配置
  4. 查看Nexus日志:docker logs nexus3
  5. 清理本地缓存:rm -rf ~/.m2/repository/com/tigeriot

8.3 无法发布SNAPSHOT

问题:发布SNAPSHOT版本时提示不允许重复部署

解决方案

在Nexus中配置 maven-snapshots 仓库:

  1. 进入 Repository > Repositories
  2. 选择 maven-snapshots
  3. 设置 Deployment policyAllow redeploy
  4. 点击 Save

8.4 SSL证书问题

问题:HTTPS连接提示证书验证失败

解决方案1:信任证书

bash 复制代码
# 导出Nexus证书
openssl s_client -showcerts -connect your-nexus-server:8081 \
  </dev/null 2>/dev/null | openssl x509 -outform PEM > nexus.crt

# 导入到Java信任库
keytool -import -alias nexus -keystore $JAVA_HOME/jre/lib/security/cacerts \
  -file nexus.crt -storepass changeit

解决方案2:使用HTTP(不推荐生产环境)

settings.xmlpom.xml 中使用 http:// 而非 https://

8.5 上传超时

问题:上传大文件时超时

解决方案

  1. 增加Nexus超时时间
  2. 使用Nginx反向代理时,增加超时配置:
nginx 复制代码
location / {
    proxy_pass http://nexus:8081;
    proxy_read_timeout 600s;
    proxy_send_timeout 600s;
    client_max_body_size 1024M;
}
  1. 在Maven中增加超时配置(pom.xml):
xml 复制代码
<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-deploy-plugin</artifactId>
      <configuration>
        <retryFailedDeploymentCount>3</retryFailedDeploymentCount>
      </configuration>
    </plugin>
  </plugins>
</build>

8.6 版本冲突

问题:依赖版本冲突

解决方案

bash 复制代码
# 查看依赖树
mvn dependency:tree

# 查看冲突
mvn dependency:tree -Dverbose

# 在pom.xml中排除冲突依赖
xml 复制代码
<dependency>
    <groupId>com.tigeriot</groupId>
    <artifactId>common-utils</artifactId>
    <version>1.0.0</version>
    <exclusions>
        <exclusion>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </exclusion>
    </exclusions>
</dependency>

8.7 磁盘空间不足

问题:Nexus磁盘空间占用过大

解决方案:配置自动清理策略

  1. 进入 Repository > Cleanup Policies

  2. 创建清理策略:

    复制代码
    Name: cleanup-snapshots
    Format: maven2
    Last downloaded: 30 days
  3. 应用到 maven-snapshots 仓库

  4. 配置定时任务(System > Tasks ):

    • Type: Cleanup repositories
    • Repository: maven-snapshots
    • Schedule: 每天凌晨3点

9. 最佳实践

9.1 版本管理策略

语义化版本

遵循语义化版本规范(Semantic Versioning):

  • 主版本号:不兼容的API变更

  • 次版本号:向下兼容的功能新增

  • 修订号:向下兼容的问题修复

    1.0.0 -> 正式发布
    1.0.1 -> Bug修复
    1.1.0 -> 新增功能
    2.0.0 -> 重大变更

SNAPSHOT vs RELEASE
  • SNAPSHOT

    • 用于开发阶段
    • 可以重复发布
    • Maven每次构建时会检查更新
    • 示例:1.0.0-SNAPSHOT
  • RELEASE

    • 用于正式发布
    • 不应重复发布(配置为Disable redeploy)
    • 稳定不变,适合生产环境
    • 示例:1.0.0

9.2 依赖管理

使用dependencyManagement

在父POM中统一管理版本:

xml 复制代码
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.tigeriot</groupId>
      <artifactId>common-utils</artifactId>
      <version>1.0.0</version>
    </dependency>
  </dependencies>
</dependencyManagement>

子模块中无需指定版本:

xml 复制代码
<dependencies>
  <dependency>
    <groupId>com.tigeriot</groupId>
    <artifactId>common-utils</artifactId>
    <!-- 版本由父POM管理 -->
  </dependency>
</dependencies>
定期更新依赖
bash 复制代码
# 检查依赖更新
mvn versions:display-dependency-updates

# 检查插件更新
mvn versions:display-plugin-updates

9.3 安全实践

1. 使用加密密码

Maven支持密码加密:

bash 复制代码
# 生成主密码
mvn --encrypt-master-password your-master-password

# 输出类似:{jSMOWnoPFgsHVpMvz5VrIt5kRbzGpI8u+9EF1iFQyJQ=}

创建 ~/.m2/settings-security.xml

xml 复制代码
<settingsSecurity>
  <master>{jSMOWnoPFgsHVpMvz5VrIt5kRbzGpI8u+9EF1iFQyJQ=}</master>
</settingsSecurity>

加密服务器密码:

bash 复制代码
mvn --encrypt-password your-server-password
# 输出类似:{COQLCE6DU6GtcS5P=}

settings.xml 中使用加密密码:

xml 复制代码
<server>
  <id>nexus-releases</id>
  <username>deployment</username>
  <password>{COQLCE6DU6GtcS5P=}</password>
</server>
2. 限制访问权限
  • 生产环境禁用匿名访问
  • 为不同角色创建专用账号
  • 定期审计用户权限
  • 使用LDAP/AD集成企业账号
3. 启用HTTPS

生产环境建议使用HTTPS:

bash 复制代码
# 使用Nginx反向代理,配置SSL证书
server {
    listen 443 ssl;
    server_name nexus.yourdomain.com;
    
    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;
    
    location / {
        proxy_pass http://nexus:8081;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

9.4 备份策略

定期备份Nexus数据
bash 复制代码
#!/bin/bash
# backup-nexus.sh

BACKUP_DIR="/data/nexus-backup"
DATE=$(date +%Y%m%d_%H%M%S)
NEXUS_DATA="/data/nexus-data"

# 创建备份目录
mkdir -p $BACKUP_DIR

# 停止Nexus(可选,推荐在线备份)
# docker stop nexus3

# 备份数据
tar -czf $BACKUP_DIR/nexus-backup-$DATE.tar.gz $NEXUS_DATA

# 启动Nexus
# docker start nexus3

# 保留最近7天的备份
find $BACKUP_DIR -name "nexus-backup-*.tar.gz" -mtime +7 -delete

echo "Backup completed: nexus-backup-$DATE.tar.gz"

配置定时任务:

bash 复制代码
# 编辑crontab
crontab -e

# 每天凌晨2点执行备份
0 2 * * * /path/to/backup-nexus.sh

9.5 性能优化

1. 调整JVM参数
yaml 复制代码
# docker-compose.yml
environment:
  - INSTALL4J_ADD_VM_PARAMS=-Xms4g -Xmx4g -XX:MaxDirectMemorySize=6g -XX:+UseG1GC
2. 配置Blob Store
  • 为不同仓库使用独立的Blob Store
  • 定期清理不用的快照版本
  • 监控磁盘使用情况
3. 启用缓存

在Maven settings.xml 中配置合理的更新策略:

xml 复制代码
<repository>
  <releases>
    <updatePolicy>daily</updatePolicy>
  </releases>
  <snapshots>
    <updatePolicy>interval:60</updatePolicy> <!-- 每60分钟 -->
  </snapshots>
</repository>

9.6 CI/CD集成

Jenkins集成示例
groovy 复制代码
pipeline {
    agent any
    
    tools {
        maven 'Maven-3.8'
        jdk 'JDK-11'
    }
    
    stages {
        stage('Checkout') {
            steps {
                git branch: 'develop', 
                    url: 'https://github.com/yourorg/yourproject.git'
            }
        }
        
        stage('Build') {
            steps {
                sh 'mvn clean package -DskipTests'
            }
        }
        
        stage('Test') {
            steps {
                sh 'mvn test'
            }
        }
        
        stage('Deploy to Nexus') {
            when {
                branch 'develop'
            }
            steps {
                sh 'mvn deploy -DskipTests'
            }
        }
        
        stage('Release') {
            when {
                branch 'master'
            }
            steps {
                script {
                    // 去掉SNAPSHOT后缀
                    sh 'mvn versions:set -DremoveSnapshot'
                    // 发布
                    sh 'mvn clean deploy -DskipTests'
                    // 升级版本并添加SNAPSHOT
                    sh 'mvn versions:set -DnextSnapshot'
                    // 提交版本变更
                    sh 'git add pom.xml'
                    sh 'git commit -m "[CI] Update version"'
                    sh 'git push origin master'
                }
            }
        }
    }
    
    post {
        success {
            echo 'Build and deploy successful!'
        }
        failure {
            echo 'Build or deploy failed!'
        }
    }
}
GitLab CI集成示例

创建 .gitlab-ci.yml

yaml 复制代码
variables:
  MAVEN_OPTS: "-Dmaven.repo.local=$CI_PROJECT_DIR/.m2/repository"

cache:
  paths:
    - .m2/repository/

stages:
  - build
  - test
  - deploy

build:
  stage: build
  image: maven:3.8-openjdk-11
  script:
    - mvn clean compile
  only:
    - branches

test:
  stage: test
  image: maven:3.8-openjdk-11
  script:
    - mvn test
  only:
    - branches

deploy-snapshot:
  stage: deploy
  image: maven:3.8-openjdk-11
  script:
    - mvn deploy -DskipTests
  only:
    - develop

deploy-release:
  stage: deploy
  image: maven:3.8-openjdk-11
  script:
    - mvn versions:set -DremoveSnapshot
    - mvn clean deploy -DskipTests
  only:
    - master
  when: manual

10. 总结

10.1 核心要点

  1. 选择合适的仓库方案:Nexus Repository是开源免费且功能强大的选择
  2. 正确配置认证:settings.xml中的server ID必须与pom.xml中的repository ID匹配
  3. 版本管理规范:开发用SNAPSHOT,发布用RELEASE
  4. 安全第一:使用加密密码、HTTPS、权限控制
  5. 定期备份:配置自动备份策略,防止数据丢失
  6. 性能优化:合理配置JVM参数和更新策略

10.2 快速参考命令

bash 复制代码
# 发布SNAPSHOT
mvn clean deploy -DskipTests

# 发布RELEASE
mvn versions:set -DremoveSnapshot
mvn clean deploy -DskipTests

# 上传第三方jar
mvn deploy:deploy-file \
  -DgroupId=com.example \
  -DartifactId=example-lib \
  -Dversion=1.0.0 \
  -Dpackaging=jar \
  -Dfile=example-lib.jar \
  -DrepositoryId=nexus-releases \
  -Durl=http://nexus:8081/repository/maven-releases/

# 更新依赖
mvn clean install -U

# 查看依赖树
mvn dependency:tree

# 清理本地缓存
mvn dependency:purge-local-repository

10.3 相关资源


文档版本 : v1.0.0
最后更新 : 2025-12-09
作者 : Tiger IoT团队
适用范围: 企业内部微服务项目


附录A:Nexus Repository URL汇总

仓库类型 仓库名称 URL
Group maven-public http://nexus:8081/repository/maven-public/
Hosted maven-releases http://nexus:8081/repository/maven-releases/
Hosted maven-snapshots http://nexus:8081/repository/maven-snapshots/
Proxy maven-central http://nexus:8081/repository/maven-central/
Proxy maven-aliyun http://nexus:8081/repository/maven-aliyun/

附录B:常用Maven命令

bash 复制代码
# 清理构建
mvn clean

# 编译
mvn compile

# 测试
mvn test

# 打包
mvn package

# 安装到本地仓库
mvn install

# 发布到远程仓库
mvn deploy

# 跳过测试
mvn clean package -DskipTests

# 更新依赖
mvn clean install -U

# 查看有效POM
mvn help:effective-pom

# 查看有效settings
mvn help:effective-settings

# 查看依赖树
mvn dependency:tree

# 分析依赖
mvn dependency:analyze

# 下载源码
mvn dependency:sources

# 版本管理
mvn versions:set -DnewVersion=2.0.0
mvn versions:set -DremoveSnapshot
mvn versions:set -DnextSnapshot
mvn versions:display-dependency-updates

附录C:settings.xml模板

提供一个完整的生产环境 settings.xml 模板,保存为独立文件方便使用:

xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                              http://maven.apache.org/xsd/settings-1.0.0.xsd">
  
  <localRepository>D:/maven-repository</localRepository>
  
  <servers>
    <server>
      <id>nexus-releases</id>
      <username>deployment</username>
      <password>{COQLCE6DU6GtcS5P=}</password>
    </server>
    <server>
      <id>nexus-snapshots</id>
      <username>deployment</username>
      <password>{COQLCE6DU6GtcS5P=}</password>
    </server>
    <server>
      <id>nexus-public</id>
      <username>developer</username>
      <password>{DFxCGMN8LQ8=}</password>
    </server>
  </servers>
  
  <mirrors>
    <mirror>
      <id>nexus-public</id>
      <mirrorOf>*</mirrorOf>
      <name>Nexus Public Repository</name>
      <url>http://your-nexus-server:8081/repository/maven-public/</url>
    </mirror>
  </mirrors>
  
  <profiles>
    <profile>
      <id>nexus</id>
      <repositories>
        <repository>
          <id>nexus-public</id>
          <name>Nexus Public Repository</name>
          <url>http://your-nexus-server:8081/repository/maven-public/</url>
          <releases>
            <enabled>true</enabled>
            <updatePolicy>daily</updatePolicy>
          </releases>
          <snapshots>
            <enabled>true</enabled>
            <updatePolicy>always</updatePolicy>
          </snapshots>
        </repository>
      </repositories>
      <pluginRepositories>
        <pluginRepository>
          <id>nexus-public</id>
          <name>Nexus Public Repository</name>
          <url>http://your-nexus-server:8081/repository/maven-public/</url>
          <releases>
            <enabled>true</enabled>
          </releases>
          <snapshots>
            <enabled>true</enabled>
          </snapshots>
        </pluginRepository>
      </pluginRepositories>
    </profile>
  </profiles>
  
  <activeProfiles>
    <activeProfile>nexus</activeProfile>
  </activeProfiles>
  
</settings>

祝您使用愉快!

相关推荐
梦未5 小时前
Spring控制反转与依赖注入
java·后端·spring
喜欢流萤吖~5 小时前
Lambda 表达式
java
ZouZou老师5 小时前
C++设计模式之适配器模式:以家具生产为例
java·设计模式·适配器模式
曼巴UE55 小时前
UE5 C++ 动态多播
java·开发语言
VX:Fegn08955 小时前
计算机毕业设计|基于springboot + vue音乐管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·课程设计
程序员鱼皮5 小时前
刚刚,IDEA 免费版发布!终于不用破解了
java·程序员·jetbrains
Hui Baby6 小时前
Nacos容灾俩种方案对比
java
曲莫终6 小时前
Java单元测试框架Junit5用法一览
java
成富6 小时前
Chat Agent UI,类似 ChatGPT 的聊天界面,Spring AI 应用的测试工具
java·人工智能·spring·ui·chatgpt