java程序 .exe启动nginx防止重复启动,已解决

2 篇文章 0 订阅
1 篇文章 0 订阅
  1. java代码生成好的.exe启动nginx服务程序
    在这里插入图片描述

  2. 根据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);
        }
    }
}
  1. 启动nginx用到的nginx.exe 和nginx图标我已经进行隐藏显示
    在这里插入图片描述
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值