java - 如何使用 JMX 监控现有的 Java 类?

标签 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");
   }

} 

最佳答案

我想看一些方法通过JMX执行了多少次,我提出这个方案

首先你需要一个类的接口(interface)。只有这个接口(interface)的方法对 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

关于java - 如何使用 JMX 监控现有的 Java 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37086601/

相关文章:

Javadocs 链接到外部 javadoc

java - 模式匹配数字/运算符

java - 何时可以在 Wicket Ajax TabbedPanel 中使用 getString()?

java - Java 中的默认字体

java - 使用接口(interface)通过两个 Activity 传递数据

java - 比较 : JMX vs JMS

web-applications - jboss的jmx-console有什么好玩的?

java - 如何创建由 jmx 公开并通过 jconsole 访问的性能计数器?

IBM Websphere 中的 Java VisualVM JMX 连接

Tomcat 线程监控 Mbeans 说明