Tomcat:使用JMX监管Tomcat的几种方式

Tomcat使用JMX管理方式,在Tomcat的自带应用manager就是使用了JMX方式来管理Tomcat,以此完成Web应用的动态部署、启动、停止。

然而manager应用是一种本地使用JMX接口的方式。对于其它的远程客户端该 怎么做呢?

方式1:JConsole客户端:

1)设置环境变量CATALINA:

set CATALINA_OPTS=-Dcom.sun.management.jmxremote
  -Dcom.sun.management.jmxremote.port=9999
  -Dcom.sun.management.jmxremote.ssl=false
  -Dcom.sun.management.jmxremote.authenticate=false

这是Windows的设置方式。

Linux /Unix 设置方式:export CATALINA_OPTS=-Dcom.sun.management.jmxremote' 'CATALINA_OPTS=-Dcom.sun.management.jmxremote' 'CATALINA_OPTS=-Dcom.sun.management.jmxremote' '-Dcom.sun.management.jmxremote.authenticate=false

网上有很多人说是设置JAVA_OPTS,建议不要这么做。

2)启动Tomcat

3)打开JConsole,设置远程连接地址:tomcat_ip:9999 

tomcat_ip 是Tomcat所在机器的IP,9999就是上面设置的端口。

方式二:使用Ant build.xml

具体使用方式参见:http://tomcat.apache.org/tomcat-6.0-doc/monitoring.html#JMXAccessorGetTask:__get_attribute_value_Ant_task

原理同下。

方式三:在Java代码中使用Ant Task

GetTask task=new GetTask();
task.setURL("http://tomcat_ip:9999/manager");
task.setUser("xxx");
task.setPassword("xxx");
Project pro=new Project();
task.setOutproperty("output");
task.setProject(pro);
task.execute();
String responseText=project.getProperty("output");

原理:使用url连接访问manager应用,从而manager使用JMX管理。

方式四:在Java代码中直接访问manager应用

public void tomcatHome(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        URL url=new URL("http://localhost:8080/manager/html");
        HttpURLConnection  conn=(HttpURLConnection)url.openConnection();
        
        conn.setAllowUserInteraction(false);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        
        conn.setDoOutput(false);
        conn.setRequestMethod("GET");
        
        conn.setRequestProperty("Accept-Charset", "utf-8");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        
        String username="admin";
        String password="admin";
        String authoInfo=new String(Base64.encode((username + ":" + password).getBytes()));
        conn.setRequestProperty("Authorization", "Basic "+authoInfo);
        conn.setRequestProperty("Connection", "keep-alive");
        conn.connect();
        
        InputStream input=conn.getInputStream();

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out= response.getWriter();
        byte[] bs=new byte[1024];
        int len=-1;
        
        while((len=input.read(bs))!=-1){
            out.write(new String(bs, 0, len));
        }
        out.flush();
        out.close();
        
    }

原理同上。

方式五:在Java中直接使用JMX API访问

参见我前面的博文 。当然了,这种方式,网络上也是常见的。

原文地址:https://www.cnblogs.com/f1194361820/p/4372767.html