简体   繁体   中英

Start and Stop Tomcat from java code

Based in a code I saw in Stackoverflow and other pages on Internet, I've created a method to stop and start tomcat at the moment I'll run a process in my system because I need to clean memory in my OS, I use System.gc() but still not enough to free memory, this is the code:

Global declaration:

private String server = "localhost";

Method to stop-start tomcat:

public void tomcat(){
    try{
        Socket s = new Socket(server,8005);
        if(s.isConnected()){
            PrintWriter print = new PrintWriter(s.getOutputStream(),true);
            print.println("SHUTDOWN"); /*Command to stop tomcat according to the line "<Server port="8005" shutdown="SHUTDOWN">" in catalina_home/conf/server.xml*/
            print.close();
            s.close();
        }
        Runtime.getRuntime().exec(System.getProperty("catalina.home")+"\\bin\\startup.bat");  /*Instruction to run tomcat after it gets stopped*/
    }catch (Exception ex){
        ex.printStackTrace();
    }
}

The code line to start tomcat works perfectly, but no the instructions to stop it because, when I instance the socket, gives me the following message: Connection refused: connect .

How can I solve this? or, is there another way to stop tomcat?

Thanks in advance.

public static void shut_server(String lien) 
{
      try {

        Process child = Runtime.getRuntime().exec(lien+"/shutdown.sh");
        System.out.println("Serveur est atteins");
    } catch (IOException ex) {
        Logger.getLogger(Installation.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("erreur de demarrage");
    }
}

lien = path to your tomcat bin file
for example - /home/zakaria/Téléchargements/apache-tomcat-8.0.21/bin

I had similar issue. I was getting the "Connection refused: connect" error message on creating the socket.

However, my use case is different from the one posted by Vlad. When the Tomcat server is starting up, my app is checking availability of some resources and if they are not, it needs to shutdown the server.

I added a 30 seconds sleep just before the line creating socket:

try {
    Thread.sleep(30000);
}
catch (Exception excp) {}
Socket socket = new Socket("localhost", port);

and it started working.

I think when Tomcat is starting up it needs some time to make the shutdown port ready to work. The selection of 30 seconds is arbitrary, it could be probably shorter.

FYI, my Tomcat is running as Windows service.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM