Maven 打包优化实战:大型分布式服务代码与依赖分离,支持自动更新常用 jar

目录

概述

🧪最终效果展示

🔧 核心配置详解(pom.xml)

1️⃣ 打包纯代码(不包含依赖)

2️⃣分离依赖:频繁更改和不更改的

3️⃣完整的build

结果

🔁 启动类自动更新 lib(支持热更新)

✅ 启动类入口调整

🔧 InitUpdateLib.java(服务启动前更新依赖)

🔄 Relauncher.java(重启服务 + 覆盖 lib)

🚀 启动命令示例

✍️结语


 

概述

在分布式架构中,我们的某些业务测试只能在客户环境下进行,部署效率直接影响测试和运维的节奏。为了解决服务包体积过大、更新慢的问题,我们对 Maven 打包方式进行了优化

将依赖按变更频率分为三类

  • 纯代码 jar(不包含依赖)

  • 更新频率低的依赖(lib)

  • 经常变更的依赖(如 SDK、DAO 等)

这样做带来了三大好处:

  • ✅ 缩短服务包传输时间

  • ✅ 提高服务更新效率

  • ✅ 提升测试与运维灵活性

🧪最终效果展示

  • ✅ 代码包单独打包,体积小、传输快

  • ✅ 依赖按修改频率拆分,更新更高效

  • ✅ 支持服务启动时自动更新依赖并重启

  • ✅ 多服务可复用本人封装的 Relauncher,简化维护

  • ✅ 兼容 Spring Boot 打包流程,配置灵活

🔧 核心配置详解(pom.xml)

1️⃣ 打包纯代码(不包含依赖)

使用 spring-boot-maven-plugin 按照下面的配置,打出来的jar就只有纯代码了

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <version>${spring.boot.version}</version>
    <configuration>
        <layout>ZIP</layout><!-- 指定打包输出格式为 ZIP 文件,而不是默认的 JAR 文件 -->
        <fork>true</fork><!-- 启动一个新进程来执行打包任务,避免在当前进程中执行 -->
        <includes>
            <!-- 无脑按照我这个配置就行,否则不生效,这里配置的是保留在jar包里面的lib没有什么用 -->
            <include>
                <groupId>nothing</groupId>
                <artifactId>nothing</artifactId>
            </include>
        </includes>
    </configuration>
    <executions>
        <execution>
            <goals>
                <!-- 执行目标为 repackage,将应用打包为可执行文件 -->
                <goal>repackage</goal>
            </goals>
        </execution>
    </executions>
</plugin>

includes 配置必须写,否则默认会将依赖打入 jar。

2️⃣分离依赖:频繁更改和不更改的

通过 maven-dependency-plugin 拷贝依赖:

<plugin>
    <!-- Apache Maven Dependency 插件,用于复制项目依赖到指定的目录 -->
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <version>3.6.0</version> <!-- 插件的版本号 -->
    <!-- 分两个1、不常用改的,2、会改的 -->
    <executions>
        <!-- 第一个 execution:将依赖复制到 lib 目录 -->
        <execution>
            <id>copy-dependencies</id> 
            <phase>package</phase> 
            <goals>
                <goal>copy-dependencies</goal> 
            </goals>
            <configuration>
                <!-- 配置复制依赖的目标路径${project.build.directory}就是打包后的 target 目录 -->
                <outputDirectory>${project.build.directory}/lib</outputDirectory> 
                <includeScope>runtime</includeScope> 
                <excludeTransitive>false</excludeTransitive> <!-- 是否排除传递性依赖,这里设置为 false,表示不排除 -->
                <stripVersion>false</stripVersion> <!-- 是否去掉版本号,设置为 false,保留版本信息 -->
            </configuration>
        </execution>

        <!-- 第二个 execution:将常用的依赖(如 API 和 DAO)复制到 classes/lib 目录 -->
        <execution>
            <id>copy-api-dao</id> <!-- 执行标识,自定义,不能重复 -->
            <phase>generate-resources</phase> <!-- 在 generate-resources 阶段执行 就是在打包前先执行,比较重要 -->
            <goals>
                <goal>copy-dependencies</goal> 
            </goals>
            <configuration>
                <!-- 配置复制依赖的目标路径,放到源码资源里面,方便后面自动更新 -->
                <outputDirectory>${project.build.directory}/classes/lib</outputDirectory> 
                
                <!-- 这里就是放你常改的包名,比如我们公司所有的sdk包名都是com.demo.*,那我配置com.demo就会匹配所有的 -->
                <includeGroupIds>com.demo</includeGroupIds> 
    
                <!-- 可以进一步配置 includeArtifactIds 来限制特定的 artifactId -->
                <!-- <includeArtifactIds>demo-dao</includeArtifactIds> -->
            </configuration>
        </execution>
    </executions>
</plugin>

1、常用依赖组件中 <phase> 必须配置为 generate-resources

      该配置的作用是在打包前(打 JAR 包前的阶段),先将经常变更的依赖库(lib)复制到资源目录中,这样才能正确打入最终的 JAR 包。如果不指定该阶段,可能会导致依赖没有被复制进去,最终包内缺失常用组件。


2、依赖筛选说明

  • includeGroupIds:用于匹配依赖的 groupId(通常对应包名前缀),多个值用英文逗号 , 分隔,例如:com.demo,org.example

  • includeArtifactIds:用于匹配具体的 artifactId,即 Maven 中的模块名,同样支持多个值用逗号分隔。

这两个配置配合使用,可以精准控制哪些依赖被复制进特定目录,灵活性非常高。

3️⃣完整的build

    <build>
        <finalName>DemoService</finalName>
        <!--单元测试时引用src/main/resources下的资源文件-->
        <testResources>
            <testResource>
                <directory>src/main/resources</directory>
            </testResource>
        </testResources>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>utf-8</source>
                    <target>1.8</target>
                    <encoding>utf-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.7.0</version>
                <configuration>
                    <layout>ZIP</layout>
                    <fork>true</fork>
                    <includes>
                        <include>
                            <groupId>nothing</groupId>
                            <artifactId>nothing</artifactId>
                        </include>
                    </includes>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>3.6.0</version>
                <executions>
                    <execution>
                        <id>copy-dependencies</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/lib</outputDirectory>
                            <includeScope>runtime</includeScope>
                            <excludeTransitive>false</excludeTransitive>
                            <stripVersion>false</stripVersion>
                        </configuration>
                    </execution>
                    <execution>
                        <id>copy-api-dao</id>
                        <phase>generate-resources</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/classes/lib</outputDirectory>
                            <includeGroupIds><!--<includeArtifactIds>通过项目名称配置<includeGroupIds>通过包名匹配-->
                                com.demo
                            </includeGroupIds>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

结果

🔁 启动类自动更新 lib(支持热更新)

因为服务运行后,jvm会占用lib,无法直接替换,那么就按照下面的逻辑去处理

✅ 启动类入口调整

在启动类写在启动前,先更新lib在重启服务。

public class DemoServiceApplication {

    public static void main(String[] args) {
        // ⬅️ 在启动前执行更新操作,入参是jar包的名称,用于二次启动
        InitUpdateLib.updateLibDependencies("DemoService"); 
        SpringApplication.run(Application.class, args);
    }

}

🔧 InitUpdateLib.java(服务启动前更新依赖)

读取 /classes/lib/ 下最新的常用依赖,复制到临时文件夹,并执行 Relaunch 更新重启。

放到项目中在启动类调用


import org.apache.commons.io.FileUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.File;
import java.io.InputStream;
import java.lang.management.ManagementFactory;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;

/**启动服务时更新常用jar
 * @author 崔cc
 * @Date:2025/4/14 20:36
 * @vesion: 0.0.1
 */
public class InitUpdateLib {
    public static void updateLibDependencies(String jarName) {
        String baseDir = System.getProperty("user.dir");
        String loaderPath = System.getProperty("loader.path");
        try {
            String startRun = System.getProperty("sun.java.command");
            if (!(startRun != null && startRun.contains(".jar"))) {
                return;
            }
            String isRelaunch = System.getProperty("relaunch"); // ← 新增
            if ("true".equals(isRelaunch)) {
                File tempDir = new File(baseDir, "lib/temp_" + jarName + "_update");
                FileUtils.deleteDirectory(tempDir);
                System.out.println("✅ 更新完成...");
                return;
            }
            System.out.println("准备更新 lib 依赖...");
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = resolver.getResources("classpath*:lib/*");

            if (StringUtil.isEmpty(loaderPath)) {
                System.out.println("❌ loader.path 未设置,跳过依赖更新");
                return;
            }

            File targetDir = new File(baseDir, loaderPath);
            if (!targetDir.exists()) targetDir.mkdirs();

            File tempDir = new File(baseDir, "lib/temp_" + jarName + "_update");
            if (!tempDir.exists()) tempDir.mkdirs();

            System.out.println("✅ 准备更新依赖");
            for (Resource resource : resources) {
                String fileName = resource.getFilename();
                File tempFile = new File(tempDir, fileName);
                try (InputStream in = resource.getInputStream()) {
                    Files.copy(in, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
                }
            }
            System.out.println("🔁 开始更新lib...");

            // 构造 relauncher.jar 的命令
            List<String> jvmArgs = ManagementFactory.getRuntimeMXBean().getInputArguments();
            List<String> command = new ArrayList<>();
            command.add("java");
            command.add("-jar");
            command.add("Relauncher.jar");
            command.add(jarName + ".jar");
            command.add(loaderPath);               // 例如: lib/pis/
            command.add("lib/temp_" + jarName + "_update");    // 临时依赖目录
            command.addAll(jvmArgs);
            ProcessBuilder pb = new ProcessBuilder(command);
            pb.inheritIO();
            pb.start();
            // 自杀退出
            System.exit(0);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("❌ 依赖更新失败");
        }
    }

🔄 Relauncher.java(重启服务 + 覆盖 lib)

  • 检查新依赖

  • 拷贝到外部 lib

  • 启动服务 ja

看类注释,我的jdk版本是1.8,可以直接cmd编译

打包好的jar和项目jar方同级目录

import java.io.IOException;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 目的,
 * 在maven打包的时候,把经常更改的jar打入服务中,启动项目时,通过这个代码去更新。
 * 启动时更新常用的jar包,使用方法
 * 直接放到文件夹里面,cmd 命令
 * 1、javac -encoding UTF-8 Relauncher.java   把java转为class
 * 2、jar cfe Relauncher.jar Relauncher Relauncher.class  把class转为可执行的jar
 * 3、把打好的jar放到和服务同级目录,多个服务如果业务一样可以服用
 * 4、启动类写了代码需要注意
 * @author 崔cc
 * @Date:2025/4/14 20:18
 * @vesion: 0.0.1
 */
public class Relauncher {
	
    private static final char[] SPINNER = {'|', '/', '-', '\\'};
    private static final String ANSI_GREEN = "\u001B[32m";
    private static final String ANSI_RESET = "\u001B[0m";

    public static void main(String[] args) throws Exception {
        if (args.length < 3) {
            System.err.println("Usage: java -jar relauncher.jar <appJar> <libDir> <newLibDir> <jvm>");
            System.exit(1);
        }

        String appJar = args[0];
        String libDir = args[1];
        String newLibDir = args[2];
        List<String> jvmArgs = Arrays.asList(args).subList(3, args.length);
        System.out.println("🔁 Relauncher started");

        // 1. 等待旧进程完全退出(防止文件锁)
        Thread.sleep(1000);

        // 2. 拷贝新 JAR 到 lib 目录
        try {
            List<Path> files = Files.walk(Paths.get(newLibDir))
                    .filter(Files::isRegularFile)
                    .collect(Collectors.toList());
            int total = files.size();
            int current = 0;

            for (Path path : files) {
				Path target = Paths.get(libDir, path.getFileName().toString());
				Files.copy(path, target, StandardCopyOption.REPLACE_EXISTING);
				current++;
				printProgressBar(current, total, "更新中");
            }
            System.out.println(); // 打印换行
			 // 4. 启动主程序
			List<String> command = new ArrayList<>();
            command.add("cmd");
            command.add("/c");
            command.add("title MyApp " + appJar); // 修改 cmd 窗口标题
            command.add("&&");
			command.add("java");
			command.addAll(jvmArgs);
			command.add("-Drelaunch=true");
			command.add("-jar");
			command.add(appJar);
			System.out.println("🚀 启动主程序: " + String.join(" ", command));

			new ProcessBuilder(command).inheritIO().start();
        } catch (IOException e) {
            System.err.println("复制新文件出错:" + e.getMessage());
			System.err.println("\n⚠️ 更新失败服务未关闭,请先关闭对应服务在重启");
        }
    }

    public static void printProgressBar(int current, int total, String prefix) {
        int barLength = 30;
        int filledLength = (int) (barLength * current / (double) total);
        String greenBar = ANSI_GREEN + repeat("=", filledLength) + ANSI_RESET;
        String emptyBar = repeat(" ", barLength - filledLength);
        int percent = (int) (100 * current / (double) total);

        char spinnerChar = SPINNER[current % SPINNER.length];
        System.out.printf("\r%s [%s%s] %d%% (%d/%d) %c", prefix, greenBar, emptyBar, percent, current, total, spinnerChar);
    }

    private static String repeat(String str, int times) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < times; i++) {
            sb.append(str);
        }
        return sb.toString();
    }
}

🚀 启动命令示例

java -Dloader.path=lib/demo/ -jar DemoService.jar

 loader.path 指定外部 lib 目录,供 Spring Boot 加载依赖。

✍️结语

通过对 Maven 打包方式的优化,我们实现了代码与依赖的分离、依赖的分层管理,以及服务启动时的依赖自动更新机制。对于经常需要远程部署、测试、热更新的分布式系统来说,这种方式能显著降低传输成本,提升部署效率和运维灵活性。希望这篇文章能对有类似需求的你带来一些启发。如果觉得有用,欢迎点赞、收藏支持一下 😊

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值