如何使用JMX监视现有Java类?

时间:2016-05-07 09:04:06

标签: java jmx

我有一个现有的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");
   }

} 

1 个答案:

答案 0 :(得分:3)

我想看看有多少时间通过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,找到正在运行的进程。

jconsole choose processs

然后你可以运行命令countMethodInvocation,你可以获得执行时间。

像这样:

Run program jconsole

本教程非常有用:

what-is-jmx-mbean-jconsole-tutorial