简体   繁体   中英

Stop Apache Tomcat using JMX

Is there any way to stop Apache Tomcat using Java and JMX?

I suppose that there is aa managed bean which can be used for this?

By its own the Tomcat does not come with the ability to shutdown operation run from the JMX , basically it is not secure !!! But if you really need it you need to create your own ShutdownMBean . It is very easy and straight forward process of creating the MBean and registering it at application deploy. Lets first create the ShutdownMBean whch will have name and will expose a single doShutdown() operation.

public interface ShutdownMBean {
    void doShutdown();
    String getName();
}

The implementation is easy as well, just send SHUTDOWN signal to default shutdown port of Tomcat.

public class Shutdown implements ShutdownMBean{

    @Override
    public void doShutdown() {
        try {
            Socket clientSocket = new Socket("localhost", 8005);
            clientSocket.getOutputStream().write("SHUTDOWN".getBytes());
            clientSocket.getOutputStream().close();
            clientSocket.close();
        } catch (IOException e) {
        }
    }

    @Override
    public String getName() {
        return "Shutdown JMX Hook";
    }

}

And at the end just register the ShutdownMBean after context initialization (I assume you are using Tomcat 7+):

@WebListener
public class ShutdownListener implements javax.servlet.ServletContextListener{

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {

    }

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        try {
            ShutdownMBean shutdownMBean = new Shutdown();
            MBeanServer server = ManagementFactory.getPlatformMBeanServer();
            ObjectName name = new ObjectName("com.example:type=Shutdown");
            server.registerMBean(shutdownMBean, name);
        } catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException | MalformedObjectNameException e) {
        }
    }
}

Thats it, just deploy your app, connect to your Tomcat using JConsole and you will find doShutdown operation under com.example group

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