用 Java 重启 Tomcat [英] Restart Tomcat with Java

查看:59
本文介绍了用 Java 重启 Tomcat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从 Java 代码重新启动 tomcat.

I need to restart the tomcat from Java code.

例如,如果某个查询在一段时间内没有被执行,那么它会自动重启tomcat.

For eg, if a query is not executed for a certain time Period then it will restart the tomcat automatically.

我尝试了以下关闭和启动代码,但是当我们关闭tomcat时,java代码不会运行,tomcat也不会启动.

I have tried the following shutdown and startup code, but when we shutdown the tomcat then the java code will not run and tomcat not started.

注意:- 我正在从应用程序运行此代码并重新启动同一个应用程序正在使用的同一个 tomact.

遵循代码

try {

    PreparedStatement.setQueryTimeout(10);
    rs = PreparedStatement.executeQuery();

} catch (SQLException ex) {

   System.out.println("IN CATCH BLOCK FOR THE REFRESH INVOICE");

   String shutcommand = "killall java";
    Process shutchild = Runtime.getRuntime().exec(shutcommand);

    System.out.println("JAVA PROCESS KILLED");

    String locationCommand = "cd /root/cluster/tomcat6/bin";
    Process locationChild = Runtime.getRuntime().exec(locationCommand);

    String strtcommand = "./startup.sh";
    Process strtchild = Runtime.getRuntime().exec(strtcommand);
}

推荐答案

TL;DR

File binaryDir = new File(System.getProperty("catalina.home") + File.separator + "bin");
String restartCommand = "\"shutdown.bat & ping 0.0.0.0 -n 4 & C:\\WINDOWS\\system32\\net start Tomcat8\"";
new ProcessBuilder("cmd", "/c", restartCommand).directory(binaryDir).start();

生存

创建新进程将在 JVM 关闭后继续存在.如果将命令组合在一行中根据我的测试和这个,它应该可以正常工作.

Creating new process will survive JVM shutdown. If you combine commands in one line it should work fine according to my tests and this.

shutdown.bat

您需要使用 shutdown.bat 来停止 Windows 服务,因为它经常在 Windows 上失败并显示消息 Cannot stop service Apache Tomcat...

You need to use shutdown.bat instead stopping windows service because it often fails on Windows with message Cannot stop service Apache Tomcat...

ping 0.0.0.0 -n 4

关机后你需要等待一段时间,否则你会得到服务已经启动.稍后再试 错误消息.另请注意,我使用 ping 代替 timeout 因为它会导致某些系统出现问题.

You need to wait some time after shutdown otherwise you will get Service is already starting. Try again later error message. Also note I use ping instead timeout because it causes problems on some systems.

C:\WINDOWS\system32\net 启动Tomcat8

我正在启动 Windows 服务,因为调用 startup.bat 对我不起作用.如果您使用不同的 tomcat 或自定义服务名称,例如 Tomcat7

I'm starting windows service because invoking startup.bat won't work for me. Also remember to replace Tomcat8 if you using different tomcat or custom service name for example Tomcat7

重定向 I/O

不要重定向流程实例或命令的输入或输出,JVM会关闭,Tomcat也不会启动.

Don't redirect input or output of process instance or command will shutdown with JVM, and Tomcat won't start.

这篇关于用 Java 重启 Tomcat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆