-
java代码生成好的.exe启动nginx服务程序
-
根据nginx占用端口来解决nginx服务重复启动问题(下面代码了解代码逻辑后根据自己的业务需求修改即可)
代码:
package org.example;import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.List;/*** @author ${USER}* @author ${DATE}*/
public class Main {public static boolean isPortUse(int port) {try (Socket socket = new Socket()) {socket.connect(new InetSocketAddress("localhost", port));return true;} catch (Exception e) {return false;}}public static int portNginxConf() {Path nginxConfPath = Paths.get(".\\conf\\nginx.conf"); // 修改为nginx.conf文件的实际路径int port = 0;try {List<String> lines = Files.readAllLines(nginxConfPath);for (String line : lines) {if (line.contains("listen")) {if (line.indexOf("#") != -1) {line = line.split("#")[0];}if (line.indexOf(";") != -1) {line = line.split(";")[0];}line = line.split("listen")[1];port = Integer.parseInt(line.trim());System.out.println("Port: " + port);break; // 如果只需要找到一个端口号,就退出循环}}} catch (IOException e) {e.printStackTrace();}return port;}public static void main(String[] args) {try {int port = portNginxConf();if (port != 0) {if (isPortUse(port) == false) {ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", "start nginx"); // /c参数表示执行后关闭CMD窗口Process process = processBuilder.start();TrayIcon trayIcon = new TrayIcon(new ImageIcon("nginx.png").getImage());SystemTray.getSystemTray().add(trayIcon);// 等待命令执行完成process.waitFor();}}} catch (AWTException e) {throw new RuntimeException(e);} catch (InterruptedException | IOException e) {throw new RuntimeException(e);}}
}
- 启动nginx用到的nginx.exe 和nginx图标我已经进行隐藏显示