建议使用install4j将glassfish作为服务安装?

时间:2017-10-23 13:32:11

标签: install4j

我们正在使用install4j版本6.1.5,我需要安装glassfish作为Windows服务。因此,我阅读了文档并尝试实现一个Windows服务包装类,以便能够为安装创建服务启动程序,以便将其用于服务操作。这是代码:

public class WindowsServiceWrapper implements Runnable {
    private static volatile boolean keepRunning = true;

    public static void main(String[] args) {
        final Thread mainThread = Thread.currentThread();

        String glassfishInstallDir = System.getProperty("installation.dir");
        if (glassfishInstallDir == null || glassfishInstallDir.isEmpty()) {
            System.err.println("Path not set to glassfish installation but required for startup the service.");
            System.exit(1);
        } else if (!new File(glassfishInstallDir).exists()) {
            System.err.println("Path '" + glassfishInstallDir + "' do not exists. Startup of the service aborted.");
            System.exit(1);
        }

        System.out.println("Starting the service.");

        String asadminPath = glassfishInstallDir + "/bin/asadmin.bat";

        CommandLine commandLine = CommandLine.parse(asadminPath + " start-domain");
        runCommand(commandLine);

        // register to jvm shutdown to handle service shutdown
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                keepRunning = false;
                try {
                    System.out.println("Shutdown of the service was triggered.");
                    mainThread.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        new WindowsServiceWrapper(asadminPath).run();
    }

    private final String ASADMIN_PATH;

    private WindowsServiceWrapper(String asadminPath) {
        ASADMIN_PATH = asadminPath;
    }

    public void run() {
        while (keepRunning) {
            // nothing to do here but waiting for shutdown hook
        }

        System.out.println("Shutdown the service.");

        CommandLine commandLine = CommandLine.parse(ASADMIN_PATH + " stop-domain");
        runCommand(commandLine);
    }

    private static int runCommand(CommandLine cmdLine) {
        DefaultExecutor executor = new DefaultExecutor();
        int exitCode;
        try {
            exitCode = executor.execute(cmdLine);
        } catch (IOException e) {
            System.out.println("Error occured during command execution: " + cmdLine.toString());
            e.printStackTrace();
            exitCode = 1;
            keepRunning = false;
        }
        return exitCode;
    }
}

为了启动和停止glassfish服务器,我使用了Apache的commons-exec库。此代码适用于安装和启动服务以及卸载服务。剩下的只有一件事:在服务启动期间,我需要等到glassfish启动完全完成并且commons-exec调用将完成。需要继续执行相关的安装步骤。现在,“Start Service”操作立即返回。我想我的包装类的主要方法被实例化为一个非成形线程,是吗?那么有一种推荐的方法来处理这样的事情吗?

1 个答案:

答案 0 :(得分:0)

您可以使用"等待HTTP服务器"等待服务器启动的操作。