IT俱乐部 Java Java工程中可执行JAR两种打包方式详解

Java工程中可执行JAR两种打包方式详解

一、需求概述

普通Java工程 docker-show 实现了定时打印docker应用信息,现在需要将其打包成可执行Jar部署到服务器端运行。

打包方式分为2种:

  • 一体化可执行包
  • 带外部依赖lib的可执行包

二、代码结构

三、运行结果

此项目使用了线程池定时打印docker应用名,端口信息

四、打包设置

1. 一体化可执行包

pom文件中引入 maven-assembly-plugin插件,核心配置

			
			maven-assembly-plugin3.5.0falsecom.fly.simple.MainRunjar-with-dependenciesmake-assemblypackagesingle

2. 带外部依赖lib的可执行包

pom文件中引入 maven-dependency-plugin、maven-jar-plugin插件,核心配置

			
			
			org.apache.maven.pluginsmaven-dependency-plugin3.1.2copy-dependenciespackagecopy-dependencies${project.build.directory}/liblombokruntimeorg.apache.maven.pluginsmaven-jar-plugin3.2.0truelibcom.fly.simple.MainRun./

五、打包运行

1. 源码放送

https://gitcode.com/00fly/demo

git clone https://gitcode.com/00fly/demo.git

或者使用下面的备份文件恢复成原始的项目代码

如何恢复,请移步查阅:神奇代码恢复工具

//goto pom-deps.xml
4.0.0com.flydocker-show0.0.1java-dependhttp://maven.apache.orgjarUTF-8UTF-81.8org.apache.logging.log4jlog4j-slf4j-impl2.12.1org.apache.commonscommons-lang33.5org.projectlomboklombok1.18.12provided${project.artifactId}org.apache.maven.pluginsmaven-compiler-plugin3.8.11.81.8maven-assembly-plugin3.5.0falsecom.fly.simple.MainRunjar-with-dependenciesmake-assemblypackagesingle
//goto pom-lib.xml
4.0.0com.flydocker-show0.0.1java-dependhttp://maven.apache.orgjarUTF-8UTF-81.8org.apache.logging.log4jlog4j-slf4j-impl2.12.1org.apache.commonscommons-lang33.5org.projectlomboklombok1.18.12provided${project.artifactId}org.apache.maven.pluginsmaven-compiler-plugin3.8.11.81.8org.apache.maven.pluginsmaven-dependency-plugin3.1.2copy-dependenciespackagecopy-dependencies${project.build.directory}/liblombokruntimeorg.apache.maven.pluginsmaven-jar-plugin3.2.0truelibcom.fly.simple.MainRun./
//goto pom.xml
4.0.0com.flydocker-show0.0.1java-dependhttp://maven.apache.orgjarUTF-8UTF-81.8org.apache.logging.log4jlog4j-slf4j-impl2.12.1org.apache.commonscommons-lang33.5org.projectlomboklombok1.18.12provided${project.artifactId}org.apache.maven.pluginsmaven-compiler-plugin3.8.11.81.8maven-assembly-plugin3.5.0truecom.fly.simple.MainRunjar-with-dependenciesmake-assemblypackagesingleorg.apache.maven.pluginsmaven-dependency-plugin3.1.2copy-dependenciespackagecopy-dependencies${project.build.directory}/liblombokruntimeorg.apache.maven.pluginsmaven-jar-plugin3.2.0truelibcom.fly.simple.MainRun./
//goto srcmainjavacomflysimpleExecutor.java
package com.fly.simple;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Executor
{
    private static String DOCKER_PS_CMD = "docker ps --format "{{.Names}} {{.Ports}}"";
    
    /**
     * execute命令
     * 
     * @param command
     * @throws IOException
     * @see [类、类#方法、类#成员]
     */
    public static List execute(String command)
        throws IOException
    {
        List resultList = new ArrayList();
        String[] cmd = SystemUtils.IS_OS_WINDOWS ? new String[] {"cmd", "/c", command} : new String[] {"/bin/sh", "-c", command};
        Process ps = Runtime.getRuntime().exec(cmd);
        try (InputStream in = ps.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)))
        {
            String line;
            while ((line = br.readLine()) != null)
            {
                resultList.add(line);
            }
        }
        return resultList;
    }
    
    /**
     * 获取docker相关信息
     * 
     * @throws IOException
     */
    @Deprecated
    public static void printPorts1()
        throws IOException
    {
        Map> map = new TreeMap();
        for (String line : execute(DOCKER_PS_CMD))
        {
            log.info("{}", line);
            String name = StringUtils.substringBefore(line, " ");
            Set ports =
                Stream.of(StringUtils.substringAfter(line, " ").split(",")).map(p -> StringUtils.substringBetween(p, ":", "->")).filter(StringUtils::isNotBlank).map(p -> p.replace(":", "")).sorted().collect(Collectors.toSet());
            map.put(name, ports);
        }
        log.info("######## {}", map);
    }
    
    /**
     * 获取docker相关信息
     * 
     * @throws IOException
     */
    public static void printPorts()
        throws IOException
    {
        Map> map = new TreeMap();
        execute(DOCKER_PS_CMD).stream()
            .map(line -> Collections.singletonMap(StringUtils.substringBefore(line, " "),
                Stream.of(StringUtils.substringAfter(line, " ").split(",")).map(p -> StringUtils.substringBetween(p, ":", "->")).filter(StringUtils::isNotBlank).map(p -> p.replace(":", "")).sorted().collect(Collectors.toSet())))
            .forEach(it -> map.putAll(it));
        log.info("######## {}", map);
    }
}
//goto srcmainjavacomflysimpleMainRun.java
package com.fly.simple;

import java.io.IOException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class MainRun
{
    /**
     * 线程池保证程序一直运行
     * 
     * @param args
     */
    public static void main(String[] args)
    {
        ScheduledExecutorService service = new ScheduledThreadPoolExecutor(1);
        service.scheduleAtFixedRate(() -> {
            try
            {
                Executor.printPorts();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }, 2, 10, TimeUnit.SECONDS);
    }
}
//goto srcmainresourceslog4j2.xml

2. 打包执行

#完整打包
mvn clean package

#一体化可执行包
mvn clean package -f pom-deps.xml

#带外部依赖lib的可执行包
mvn clean package -f pom-lib.xml

3. 打包结果

到此这篇关于Java工程中可执行JAR两种打包方式详解的文章就介绍到这了,更多相关Java打包可执行JAR内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!

本文收集自网络,不代表IT俱乐部立场,转载请注明出处。https://www.2it.club/code/java/10732.html
上一篇
下一篇
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 1120393934@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部