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訪問
參見我前面的博文 。當然了,這種方式,網絡上也是常見的。