JXM 监控tomcat 7(含代码

时间:2021-06-17 16:53:20
1.在tomcat的server.xml中加入:
<Listener className="org.apache.catalina.mbeans.JmxRemoteLifecycleListener" rmiRegistryPortPlatform="10001" rmiServerPortPlatform="10002" />
 
2. 将jdk目录/jre/lib/management下的jmxremote.access、jmxremote.password两个文件放到 CATALINA_HOME/conf目录里面,如果没有jmxremote.password,则从JAVA_HOME/jre/lib /management/jmxremote.password.template拷贝出一个名为jmxremote.password的新文件, 修改文件内容:
jmxremote.password 文件末尾:
admin bibo
jmxremote.access 文件末尾:
admin read #(这里只要有read权限就够了,不需要readwrite)
 
ps:帐号是admin,密码是bibo
 
3.将catalina-jmx-remote.jar加入tomcat目录/lib下
4.修改tomcat  /bin/catalina.bat
在rem ----- Execute The Requested Command 下加入
windows下:
set JAVA_OPTS= -Dcom.sun.management.jmxremote.password.file=../conf/jmxremote.password -Dcom.sun.management.jmxremote.access.file=../conf/jmxremote.access -Dcom.sun.management.jmxremote.ssl=false
linux下:
CATALINA_OPTS=" -Djava.rmi.server.hostname=192.168.2.201 -Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.ssl=false
-Dcom.sun.management.jmxremote.authenticate=true
-Dcom.sun.management.jmxremote.password.file=../conf/jmxremote.password
-Dcom.sun.management.jmxremote.access.file=../conf/jmxremote.access"
注意如果要从其他机器通过jconsole连接的话,就一定要有 -Djava.rmi.server.hostname=192.168.2.201,否则会连接不上
 
附件:
https://app.yinxiang.com/shard/s41/res/a2fc563b-0be3-4b43-abc9-6b54061c672e/catalina-jmx-remote.jar
 
代码:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;



public class TomcatMonitor {
public static String host="127.0.0.1";
public static String port="10001";
public static String user="monitor";
public static String pwd="adchina";
public static String connector="\"http-bio-8080\"";
public static String basepath="/monitordata";
public static void main(String[] args) throws IOException{
Parser(args);
String jmxUrl="service:jmx:rmi:///jndi/rmi://"+host+":"+port+"/jmxrmi";
int jvm_memory_free=0;
int jvm_memory_max=0;
int jvm_memory_total=0;

int connector_max_time=0;
int connector_error_count=0;
int connector_bytes_sent=0;
int connector_processing_time=0;
int connector_request_count=0;
int connector_bytes_received=0;

int connector_current_thread_count=0;
int connector_min_spare_threads=0;
int connector_max_threads=0;
int connector_max_spare_threads=0;
int connector_current_threads_busy=0;
JMXConnector jmxConnector =null;
try {
JMXServiceURL serviceURL=new JMXServiceURL(jmxUrl);
Map<String,String[]> map=new HashMap<String,String[]>();
String[] credentials = new String[] { user, pwd };
map.put("jmx.remote.credentials", credentials);
jmxConnector = JMXConnectorFactory.connect(serviceURL, map);
MBeanServerConnection mbsc = jmxConnector.getMBeanServerConnection();
ObjectName threadObjName = new ObjectName("Catalina:type=ThreadPool,name="+connector+"");
connector_current_thread_count=Integer.parseInt(mbsc.getAttribute(threadObjName, "currentThreadCount").toString());
connector_min_spare_threads=Integer.parseInt(mbsc.getAttribute(threadObjName, "minSpareThreads").toString());
connector_max_threads=Integer.parseInt(mbsc.getAttribute(threadObjName, "maxThreads").toString());
//if(mbsc.getAttribute(threadObjName, "maxSpareThreads")!=null)
// connector_max_spare_threads=Integer.parseInt(mbsc.getAttribute(threadObjName, "maxSpareThreads").toString());
connector_current_threads_busy=Integer.parseInt(mbsc.getAttribute(threadObjName, "currentThreadsBusy").toString());

ObjectName requestObjectName=new ObjectName("Catalina:type=RequestProcessor,worker=\"http-bio-8080\",name=HttpRequest1");
connector_max_time=Integer.parseInt(mbsc.getAttribute(requestObjectName, "maxTime").toString());
connector_error_count=Integer.parseInt(mbsc.getAttribute(requestObjectName, "errorCount").toString());
connector_bytes_sent=Integer.parseInt(mbsc.getAttribute(requestObjectName, "bytesSent").toString());
connector_processing_time=Integer.parseInt(mbsc.getAttribute(requestObjectName, "processingTime").toString());
connector_request_count=Integer.parseInt(mbsc.getAttribute(requestObjectName, "requestCount").toString());
connector_bytes_received=Integer.parseInt(mbsc.getAttribute(requestObjectName, "bytesReceived").toString());

String output_str="jvm_memory_free:"+jvm_memory_free+" jvm_memory_max:"+jvm_memory_max+" jvm_memory_total:"+jvm_memory_total+
" connector_max_time:"+connector_max_time+" connector_error_count:"+connector_error_count+" connector_bytes_sent:"+connector_bytes_sent+" connector_bytes_received:"+connector_bytes_received+
" connector_processing_time:"+connector_processing_time+" connector_request_count:"+connector_request_count+" connector_current_thread_count:"+connector_current_thread_count+
" connector_min_spare_threads:"+connector_min_spare_threads+" connector_max_threads:"+connector_max_threads+" connector_max_spare_threads:"+connector_max_spare_threads+
" connector_current_threads_busy:"+connector_current_threads_busy;
saveDataToFile(output_str);
} catch (Exception e) {
errorLog(e.getMessage());
}
finally
{
if(connector!=null)
{
try {
jmxConnector.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

public static void Parser(String[] args)
{
Map<String, String> opt=new HashMap<String,String>();
for(int i=0;i<args.length;i++){
if(args[i].equals("-h")||args[i].equals("--help"))
{
System.out.println("-h,--help show this help message and exit");
System.out.println("-H HOST tomcat server host");
System.out.println("-P PORT tomcat server port");
System.out.println("-u USER jmx user");
System.out.println("-p PWD jmx password");
System.out.println("--path BASEPATH data & log file base path");
System.exit(0);
}
if(args[i].startsWith("-")&&(i+1)<args.length){
opt.put(args[i], args[i+1]);
}
}
host=opt.containsKey("-H")?opt.get("-H"):host;
port=opt.containsKey("-P")?opt.get("-P"):port;
user=opt.containsKey("-u")?opt.get("-u"):user;
pwd=opt.containsKey("-p")?opt.get("-p"):pwd;
connector=opt.containsKey("-c")?opt.get("-c"):connector;
basepath=opt.containsKey("--path")?opt.get("--path"):basepath;
}

public static void saveDataToFile(String data_str) throws IOException
{
Date dt=new Date();
String date= new SimpleDateFormat("yyyy.MM.dd").format(dt);
String now=new SimpleDateFormat("HH.mm.ss").format(dt);
String path=basepath+"/Tomcat/data/"+date+"/";
File directory=new File(path);
if(!directory.exists())
directory.mkdirs();
String filePath=path+now+".csv";
File dataFile=new File(filePath);
if(!dataFile.exists())
dataFile.createNewFile();
FileOutputStream fos = new FileOutputStream(filePath,true);
fos.write(data_str.getBytes());
fos.close();
}

public static void errorLog(String mes) throws IOException{
Date dt=new Date();
String date= new SimpleDateFormat("yyyy.MM.dd").format(dt);
String now=new SimpleDateFormat("HH:mm:ss").format(dt);
String path=basepath+"/Tomcat/log/";
File directory=new File(path);
if(!directory.exists())
directory.mkdirs();
String filePath=path+date+".csv";
File dataFile=new File(filePath);
if(!dataFile.exists())
dataFile.createNewFile();
FileOutputStream fos = new FileOutputStream(filePath,true);
fos.write(("["+now+"]:"+mes+"\r\n").getBytes());
fos.close();
}
}