cmd中根据启动命令查找jar进程的pid,cmd中结束指定jar进程

一、获取pid

wmic process where "name like '%java%' and commandline like '%[启动命令行中写的jar包名称,确保唯一]%' " get processid

二、根据pid结束进程(若大家有其他方式获取pid,可跳过第一步)

taskkill /f /pid 16430

此处贴我的springboot中启动、结束jar及其他应用(nginx等)方法

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;

import static java.util.concurrent.Executors.newFixedThreadPool;
public class Service {

private List<String> processServer = new ArrayList<String>() {{
    add("nginx");
    add("redis");
    add("mysql");
}};
//启动服务命令
private final static Map<String, String> startServerCmd = new HashMap<String, String>() {
    {
        put("nginx", "start nginx.bat");
        put("dbWeb", " start dbWeb.bat ");
        put("redis", " start redis.bat ");
        put("mysql", " start mysql.bat ");
        put("eureka", " start eureka.bat ");
        put("clear", " start clear.bat ");
        put("inte", " start inte.bat ");
        put("jdbc", " start jdbc.bat ");
        put("sys", " start sys.bat ");
    }
};
//停止服务命令
private final static Map<String, String> stopServerCmd = new HashMap<String, String>() {
    {
        put("nginx", "start nginx-stop.bat");
        put("redis", " start redis-stop.bat ");
        put("mysql", " start mysql-stop.bat ");
    }
};
//检查服务有无开启
private final static Map<String, String> examineServerCmd = new HashMap<String, String>() {
    {
        put("nginx", "nginx.exe");
        put("redis", "redis-server.exe");
        put("mysql", "mysqld.exe");

        put("dbWeb", "dbWeb.jar");
        put("eureka", "eureka_server.jar");
        put("clear", "data_clear_server.jar");
        put("inte", "integration.jar");
        put("jdbc", "jdbc_server.jar");
        put("sys", "system-options.jar");
    }
};

//检查服务有无开启
public boolean examineServer(String serverName) {
    String cmd = examineServerCmd.get(serverName);
    if (processServer.contains(serverName)) {
        return findProcess(cmd);
    } else {
        return findJar(cmd);
    }
}

//启动服务
public void startServer(String serverName) {
    String cmd = startServerCmd.get(serverName);
    try {
        executeCmd(cmd);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

//停止服务
public void stopServer(String serverName) {
    String server = examineServerCmd.get(serverName);
    if (processServer.contains(serverName)) {
        //结束进程
        String cmd = stopServerCmd.get(serverName);
        try {
            executeCmd(cmd);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        //结束jar服务
        List<Integer> jarPid = findJarPid(server);
        for (int pid : jarPid) {
            dieByPid(pid);
        }
    }
}

//判断进程是否开启
private static boolean findProcess(String processName) {
    BufferedReader bufferedReader = null;
    try {
        String cmd = "tasklist -fi " + '"' + "imagename eq " + processName + '"';
        Process proc = Runtime.getRuntime().exec(cmd);
        bufferedReader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            if (line.contains(processName)) {
                return true;
            }
        }
        return false;
    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}

//判断jar是否启动
private static boolean findJar(String jarName) {
    BufferedReader bufferedReader = null;
    try {
        String cmd = "wmic process where " + '"' +
                "name like '%java%' and commandline like '%" + jarName + "%' " + '"' + " get processid,commandline ";
        Process proc = Runtime.getRuntime().exec(cmd);
        bufferedReader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            if (line.contains(jarName)) {
                return true;
            }
        }
        return false;
    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (Exception ex) {
            }
        }
    }
}

//获取jar pid
private static List<Integer> findJarPid(String jarName) {
    BufferedReader bufferedReader = null;
    List<Integer> pid = new ArrayList<>();
    try {
        String cmd = "wmic process where " + '"' +
                "name like '%java%' and commandline like '%" + jarName + "%' " + '"' + " get processid";
        Process proc = Runtime.getRuntime().exec(cmd);
        bufferedReader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            if (!line.contains("ProcessId") && !"".equals(line)) {
                line = line.replace(" ", "");
                pid.add(Integer.parseInt(line));
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (Exception ex) {
            }
        }
    }
    return pid;
}

//终止pid
private static void dieByPid(Integer pid) {
    String cmd = "taskkill /pid " + pid + "  -t -f";
    try {
        String executeCmd = executeCmd(cmd);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

//打开配置文件
private void openConf(String path) {
    String cmd = "notepad " + path;
    try {
        executeCmd(cmd);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private String workPath = System.getProperty("user.dir")+"/../";//当前根目录
private String applicationPath = workPath + "/application/";//jar初始配置目录
private List<String> txtShow = new ArrayList<String>() {{
    add("nginx");
    add("mysql");
    add("redis");
}};//需要用记事本打开的方法

private List<String> jarConfName = new ArrayList<String>() {{
    add("application.properties");
    add("application.yml");
}};//jar的配置文件名称
private Map<String,String> outherConfName = new HashMap<String, String>(){{
    put("nginx","/nginx/conf/nginx.conf");
    put("redis","/redis/redis.windows.conf");
    put("mysql","/mysql/my.ini");
}};//其他配置文件名称

//打开配置文件用线程
private ExecutorService exec = newFixedThreadPool(15);

//检测缺失的配置文件,将文件进行复制
List<String> deficiencyConfFile(String serverName) {
    List<String> confNameList = new ArrayList<>();
    if (!txtShow.contains(serverName)) {
        //jar服务,检查application文件数目
        String path = applicationPath + serverName;
        File file = new File(path);
        File[] sourceFiles = file.listFiles(item -> (item.isFile() && jarConfName.contains(item.getName())));
        if (sourceFiles == null) {
            System.out.println("未找到配置文件");
            confNameList.add("error");
            return confNameList;
        }
        List<File> sourcefileList = Arrays.asList(sourceFiles);
        //获取完初始的配置文件后,去jar目录对比配置文件数量

        //网站后台程序,目录不同
        path = "dbWeb".equals(serverName) ? workPath + "/" + serverName : workPath + "/jar/" + serverName;
        file = new File(path);

        File[] targetFiles = file.listFiles(item -> (item.isFile() && jarConfName.contains(item.getName())));//jar中的配置文件数
        if (targetFiles != null) {
            List<String> targetConfList = new ArrayList<>();
            for (File file1 : targetFiles) {
                targetConfList.add(file1.getName());
            }

            //jar服务的目录下已有配置文件,移除已有的
            sourcefileList = new ArrayList<>(sourcefileList);
            for (int i = sourcefileList.size() - 1; i >= 0; i--) {
                if (targetConfList.contains(sourcefileList.get(i).getName())) {
                    sourcefileList.remove(i);
                }
            }
            for (File file1 : sourcefileList) {
                String outPath = path + "/" + file1.getName();
                Path sourcePath = Paths.get(file1.getPath());
                Path outPath1 = Paths.get(outPath);
                try {
                    Files.copy(sourcePath, outPath1);
                    confNameList.add(file1.getName());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (confNameList.size() > 0) {
            System.out.println(serverName + "服务配置文件初始化成功,共加载" + confNameList.size() + "个文件,其中包含: \n" + String.join("\n", confNameList));
            }
        }
    }
    return confNameList;
}

void openJarConf(String serverName) {
    String path = "dbWeb".equals(serverName) ? workPath + "/" + serverName : workPath + "/jar/" + serverName;
    File file = new File(path);
    File[] targetFiles = file.listFiles(item -> (item.isFile() && jarConfName.contains(item.getName())));//jar中的配置文件数

    if (targetFiles != null) {
        for (File file1 : targetFiles) {
            exec.execute(() -> {
                openConf(file1.getPath());
            });
        }
    } else {
        fileNotExit(path);
    }
    System.out.println(((ThreadPoolExecutor)exec).getActiveCount());
}
void openOutherConf(String serverName) {
    String path = workPath+outherConfName.get(serverName);
    File file = new File(path);
    if(!file.isFile()){
        fileNotExit(path);
        return;
    }
    exec.execute(()->{
        openConf(path);
    });
}
private void fileNotExit(String path){
System.out.println("未找到配置文件,建议检查目录、文件名称("+path+")或重新安装以获取配置文件");
}

//windows执行cmd
private static String executeCmd(String command) throws IOException {
    Runtime runtime = Runtime.getRuntime();
    Process process = runtime.exec("cmd /c " + command);
    BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
    String line;
    StringBuilder build = new StringBuilder();
    while ((line = br.readLine()) != null) {
        build.append(line);
    }
    return build.toString();
}

//linux执行cmd
private static String executeLinuxCmd(String command) throws IOException {
    Runtime runtime = Runtime.getRuntime();
    Process process = runtime.exec(command);
    BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
    String line = null;
    StringBuilder build = new StringBuilder();
    while ((line = br.readLine()) != null) {
        System.out.println(line);
        build.append(line);
    }
    return build.toString();
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java jar启动命令有多种方式,具体使用哪种方式取决于你的需求和场景。以下是几种常见的启动命令: 1. 使用命令启动:可以使用命令`java -jar test.jar`来启动一个Java jar包。这种方式会在当前的命令行窗口执行,并且如果你使用Ctrl+C来退出启动页面,程序将会断运行。 2. 使用后台运行命令:如果你希望在后台运行启动进程,可以使用`java -jar test.jar &`来启动。这样可以让程序在后台运行,而你可以继续使用命令行做其他操作。同样地,如果你使用Ctrl+C来退出启动页面,程序也会断运行。 3. 使用nohup命令:如果你希望在退出启动页面后,程序仍然继续在后台运行,可以使用nohup命令。例如,`nohup java -jar test.jar &`。这样会将程序转为后台运行,并且不会受到Ctrl+C的影响。 需要注意的是,不同的启动命令会有一些细微的差别,你可以根据自己的需求选择适合的方式来启动Java jar包。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [jar包的各种启动方式总结](https://blog.csdn.net/m0_46897923/article/details/127549481)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值