4

如何在没有 JConsole 的情况下使用 JMX 执行方法?

我想通过 Java 代码中的 JMX 调用方法。使用下面的代码,我可以获得MBean 接口的所有方法的名称,但我还不能真正执行它们。仍然缺少一些东西,有人可以帮我吗?

private static String connectJmx() {
    StringBuilder sb = new StringBuilder();

    JMXServiceURL serviceUrl;
    JMXConnector jmxConnector = null;
    try {
        serviceUrl = new JMXServiceURL(URL);
        jmxConnector = JMXConnectorFactory.connect(serviceUrl, null);
        MBeanServerConnection mbeanConn = jmxConnector.getMBeanServerConnection();

        ObjectName objectName = ObjectNameProvider.getObjectName();
        MBeanInfo info = mbeanConn.getMBeanInfo(objectName);

        MBeanOperationInfo[] operations = info.getOperations();         
        for (int i = 0; i < operations.length; i++) {
         sb.append(operations[i].getName()).append("\n");
        }

    }
    catch (Exception e) {
        LogManager.doLog(LOG, LOGLEVEL.INFO, "exception connection jmx",  e);

    } finally {
        try {
            if(jmxConnector != null){
                jmxConnector.close();
            }
        } catch (IOException e) {
        //
        }
    }       
    return sb.toString();
}

上面的 for 循环收集方法的名称。我想要类似的东西,而不是收集名称,而是实际执行它们。请不要推荐 JConsole,因为其他原因它不起作用。

4

2 回答 2

3

您还没有放置代码来调用 mbean 方法。这是一个示例代码,可以帮助您:

import javax.management.*;
import javax.management.remote.*;
import com.sun.messaging.AdminConnectionFactory;
import com.sun.messaging.jms.management.server.*;


public class  InvokeOp
  { 
    public static void  main (String[]  args)
      { 
        try
          { //  Create administration connection factory
                AdminConnectionFactory  acf = new AdminConnectionFactory();

            //  Get JMX connector, supplying user name and password
                JMXConnector  jmxc = acf.createConnection("AliBaba", "sesame");

            //  Get MBean server connection
                MBeanServerConnection  mbsc = jmxc.getMBeanServerConnection();

            //  Create object name
                ObjectName  serviceConfigName = MQObjectName.createServiceConfig("jms");

            //  Invoke operation
                mbsc.invoke(serviceConfigName, ServiceOperations.PAUSE, null, null);

            //  Close JMX connector
                jmxc.close();
          }

        catch (Exception  e)
          { System.out.println( "Exception occurred: " + e.toString() );
            e.printStackTrace();
          }
      }
  }
于 2013-05-16T09:41:36.760 回答
0

查看 MBeanServerConnection JavaDoc,尤其是调用方法: http://docs.oracle.com/javase/6/docs/api/javax/management/MBeanServerConnection.html#invoke(javax.management.ObjectName, java.lang.String , java.lang.Object[], java.lang.String[])

于 2013-05-16T09:41:45.620 回答