我有一个如下的现有Java类,并且我想使用JMX监视此类中每个方法的方法调用数。我该怎么做?我尝试了谷歌,但我看不到整个事情如何联系的大局。如果能看到一些代码示例,那将是非常不错的
Public class RPCServer {
public void storeSchema() { // want to count number of method invocations
System.out.println("storeSchema");
}
public void getSchema() { // want to count number of method invocations
System.out.println("getSchema");
}
public void storeRow() { // want to count number of method invocations
System.out.println("storeRow");
}
public void getRow() { //want to count number of method invocations
System.out.println("getRow");
}
}
我想看看通过JMX执行某些方法有多少次,我提出了这种解决方案
首先,您需要一个用于类的接口。对于JMX,仅此接口的方法可见:
public interface RPCServerInterface {
int countMethodInvocation(String method);
}
然后在该类中,存储每个函数被调用多少次。
public class RPCServer implements RPCServerInterface{
private int row;
private Map<String,Integer> countByMethod = new HashMap<String,Integer>();
// +1 to the number of time of execution of this method
private void sumMethodInvocation(String method) {
if ( countByMethod.containsKey(method) ) {
int n = countByMethod.get(method);
countByMethod.put(method, n+1);
} else {
countByMethod.put(method,1);
}
}
// how many time the method has been invoked
@Override
public int countMethodInvocation(String method){
return countByMethod.containsKey(method)?countByMethod.get(method):0;
}
public void setRow(int i) {
// register each time is executed
this.sumMethodInvocation("setRow");
this.row = i;
}
public int getRow() {
// register each time is executed
this.sumMethodInvocation("getRow");
return row;
}
}}
}
然后,您必须注册您的Bean:
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
RPCServer rpcServer = new RPCServer();
ObjectName objectName = new ObjectName("org.foo.RPCServer.jmx:type=RPCServerInterface");
StandardMBean standardMBean = new StandardMBean(rpcServer,RPCServerInterface.class);
mBeanServer.registerMBean(standardMBean, objectName);
路径org.foo.RPCServer.jmx是任意的。
然后,您运行jconsole并找到正在运行的进程。
然后,您可以运行命令countMethodInvocation并获取执行时间。
像这样:
本教程可能会有用:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句